Using a blocking, streaming .NET socket I'm connecting to a server. Whenever I'm reading small bits of data, all goes well and the data is received into my buffer:
using (var socket = new Socket(SocketType.Stream, ProtocolType.IP))
{
socket.Connect(IPAddress.Parse("127.0.0.1"), 5000);
byte[] buffer = new byte[BufferSize];
socket.Receive(buffer);
// Here buffer doesn't always contain all data the server sent me?
Console.WriteLine(Encoding.Default.GetString(buffer));
}
In some cases though, I'm not receiving everything the server sends me. Data seems to be chopped off. What can be the cause of this?
This is documented in the
Receive()
method, emphasis mine:When ignoring the return value, you will not know what portion of your buffer actually contains relevant data. Depending on the protocol being used, you may or may not know the content length in advance. Some protocols provide this length, others close the connection when done, yet another can use a message boundary.
You'll have to hold the received data in another buffer, and return or output the entire message buffer when no more data is available or expected. This can be done like this:
The received bytes are ASCII characters (as defined in the made-up protocol), so each byte received indicates one character (you can't convert partially received multibyte unicode characters). The bytes are converted to a string and appended to the
message
variable. The code loops until the server closes the connection.When the message size is known on beforehand, again, depending on the protocol being used, you can create a message buffer and copy the data there on each
Receive()
:This can in turn be put in a resuable method:
There's the
NetworkStream
which wraps a socket, but it has the same reading issues as the socket itself. You will have to monitor the return value and keep callingRead()
until you've received all bytes. Same goes for theTcpClient
that has aGetStream()
method, on whose return value you'll also have to continue reading until you've read all data.