I receive a message from the server on the socket. The Receive method takes byte[] as a parameter, and since I do not know what size the message will be, I allocate memory with a margin of, for example, 100 bytes.

 byte[] byteMessage = new byte[100]; socket.Receive(byteMessage); 

After receiving I convert to string using:

 string strMessage = Encoding.Default.GetString(byteMessage); 

As a result, the string strMessage is a string that I need, but with a bunch of spaces at the end.

Questions:

  1. Can I get the size of the received message by socket?
  2. If not, how to determine the end of the received message?
  • one
    Necroposting, of course, but: DO NOT use Encoding.Default . Because Encoding.Default means ANSI-encoding on the client, which with great probability does not coincide with the encoding in which the server sends the data. - VladD

2 answers 2

Perhaps you should use the value returned by the Receive method, which, as MSDN suggests, is nothing more than the number of bytes received. However, if this is not the case (to be honest, I did not check it), then you can do this:

 string strMessage = Encoding.Default.GetString(bytes.Where(x => x != 0).ToArray()); 
  • Thank! Indeed Receive returns the number of bytes transferred. - masuhorukov

Receive returns the number of bytes read. There is also an overloaded Receive method, use it.

Example

  var buffer = new byte[128]; string mes = string.Empty; do { int count = socket.Receive(buffer, buffer.Length, 0); mes += Encoding.UTF8.GetString(buffer, 0, count); } while(socket.Available > 0)