I'm using TCP sockets. The client just not receive the packets, it don't have any exception.
There are plenty of answers about this. You real problem is that you have not understood what stream based protocols means. With TCP you do not send messages, you send streams of bytes.
As a result, the receiver side can not assume that everything received in one socket.Receive
corresponds to exactly the same bytes as the other side sent using socket.Send
.
You should therefore use some sort of mechanism to detect when a complete message have been received. Typically you either prefix each of your messages with a length prefix or use a delimiter after each message.
The reason to why it works when you use a Thread.Sleep
is that the messages are short enough to be sent one at a time and you manage to receive them before the next message is sent. Without the delay, the nagle algorithm probably comes into play and merge your messages.
A naive implementation:
public void Send(byte[] msg)
{
var header = BitConverter.GetBytes(msg.Length);
socket.Send(header, 0, header.Length);
socket.Send(msg, 0, msg.Length);
}
Receiver side (probably faulty, but should give you a hint):
var buffer = new byte[4];
int bytesReceived = socket.Receive(buffer, 0, 4, ....);
if (bytesReceived < 4)
{
bytesReceived = socket.Receive(buffer, bytesReceived, 4 - bytesReceived, ....);
//this can fail too, probably should use a loop like below until
//all four length bytes have been received.
}
var bytesToRead = BitConverter.GetInt32(buffer, 0);
var buffer = new byte[bytesToRead];
var offset = 0;
while (bytesToRead > 0)
{
var len = Math.Min(bytesToRead, buffer.Length);
var read = socket.Receive(buffer, offset, len, .....);
bytesToRead -= read;
offset += read;
}
//now you got everything.