I have a C# application which sends more than 600,000 bytes to the server. The response from the server has more than 10,000 bytes. The problem I have is when I read more than 10k bytes it throws an exception:
System.Net.Sockets.SocketException: An existing connection was
forcibly closed b y the remote host at
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32
size,SocketFlags socketFlags) at
System.Net.Sockets.Socket.Receive(Byte[] buffer) at
SimpleTcpClient.Main(String[] args)
My code:
byte[] data = new byte[10000];
int receivedDataLength = server.Receive(data);
string Data = Encoding.ASCII.GetString(data, 0, receivedDataLength);
When you use sockets you must anticipate that the socket might transfer fewer bytes than you expect. You must loop on the .Receive method to get the remainder of the bytes.
This is also true when you send bytes through a socket. You must check how many bytes were sent, and loop on the Send until all bytes have been sent.
This behavior is due to the network layers splitting the messages into multiple packets. If your messages are short, then you are less likely to encounter this. But you should always code for it.
With more bytes per buffer you are very likely to see the sender’s message spit into multiple packets. Each read operation will receive one packet, which is only part of your message. But small buffers might also be split.