I send it like this:

byte[] data = Encoding.Unicode.GetBytes(message); stream.Write(data, 0, data.Length); 

I accept it like this:

  byte[] data = new byte[64]; // буфер для получаемых данных while (true) { // получаем сообщение StringBuilder builder = new StringBuilder(); int bytes = 0; do { bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); } while (stream.DataAvailable); string message = builder.ToString(); Console.WriteLine(message); // TODO } 

Such a method is suitable for passing a string or say int. And how to transfer an array and in addition to complex numbers Complex [] ??

  • one
    Serialize to stream and pass it. And it is better to read from the stream not through while (DataAvailable) - what if the server will transfer more slowly than the client read? - VladD
  • How then to read? - zaki hatfild
  • one
    Transmit the length of the data at the beginning, and first read the length and then the required number of data bytes from the stream (via while (totalBytes < neededBytes) totalBytes += await stream.ReadAsync(...); ). - VladD
  • 2
    And I came to the conclusion that if 0 bytes are read, then everything is already complete, the channel is closed and you can go out. Not sure what is right, but it seems to work. Not everywhere because the length is sent. So it’s right to read lengthwise, but you can't go out by DataAvailable - vitidev
  • 2
    You can also try to take any of the streaming serializers to feed the NetworkStream to him and then he will take on the formation of a byte message, which he himself can read on the other side, and not be tricky with transport. - vitidev

1 answer 1

Some such example should work:

Sending side:

 async Task SendComplex(Stream s, Complex c) { var reBytes = BitConverter.GetBytes(c.Real); await s.WriteAsync(reBytes, 0, reBytes.Length); var imBytes = BitConverter.GetBytes(c.Imaginary); await s.WriteAsync(imBytes, 0, imBytes.Length); } async Task SendInt32(Stream s, int n) { var bytes = BitConverter.GetBytes(n); await s.WriteAsync(bytes, 0, bytes.Length); } async Task SendComplexArray(Stream s, Complex[] array) { await SendInt32(s, array.Length); foreach (var c in array) await SendComplex(s, c); } 

The host:

 async Task<byte[]> ReceiveBytes(Stream s, int nbytes) { var buf = new byte[nbytes]; var readpos = 0; while (readpos < nbytes) readpos += await s.ReadAsync(buf, readpos, nbytes - readpos); return buf; } Task<int> ReceiveInt32(Stream s) { var bytes = await ReceiveBytes(s, 4); return BitConverter.ToInt32(bytes, 0); } Task<Complex> ReceiveComplex(Stream s) { var bytes = await ReceiveBytes(s, 16); // 8 bytes re + 8 bytes im var re = BitConverter.ToDouble(bytes, 0); var im = BitConverter.ToDouble(bytes, 8); return new Complex(re, im); } Task<Complex[]> ReceiveComplexArray(Stream s) { var array = new Complex[await ReceiveInt32(s)]; for (int i = 0; i < array.Length; i++) array[i] = await ReceiveComplex(s); return array; }