したがって、クライアント/サーバープログラム間の通信でこのコードが正常に機能しました。通信は、後続のバイト数を指定する int と「ペイロード」の 2 つの要素を持つ 1 バイトのバッファで行われます。デバッガーを使用してステップスルーして確認する場合。私のコードが行に到達したとき
await cStream.ReadAsync(bytes, 0, 4)
;
使用可能なバイト数を確認すると、32 と表示されます。この行を通過すると、使用可能なバイト数が 0 であると表示されます。_stream (TcpClient の NetworkStream) から直接読み取ると、コードは問題なく動作します。
完全なコードは
private async void RecvAsync()
{
byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
RijndaelManaged crypto = new RijndaelManaged();
CryptoStream cStream = new CryptoStream(_stream, crypto.CreateDecryptor(key, iv), CryptoStreamMode.Read);
int bytesRead = 0;
do
{
try
{
byte[] bytes = new byte[4];
await cStream.ReadAsync( bytes, 0, 4 );
//await _stream.ReadAsync(bytes, 0, 4, _cancelToken.Token);
int size = BitConverter.ToInt32(bytes, 0);
cStream = new CryptoStream(_stream, crypto.CreateDecryptor(key, iv), CryptoStreamMode.Read);
bytes = new byte[size];
bytesRead = cStream.Read( bytes, 0, size );
//await _stream.ReadAsync(bytes, 0, bytes.Length, _cancelToken.Token); //_stream.Read( bytes, 0, size );
int id = BitConverter.ToInt32( bytes, 0 );
int type = BitConverter.ToInt32( bytes, 4 );
UTF8Encoding utf = new UTF8Encoding();
string body = utf.GetString( bytes, 8, size - 8 );
Packet packet = new Packet( id, (ServerDataType)type, body );
ProcessPacket( packet );
}
catch ( Exception ) { break; }
} while ( bytesRead > 0 );
}