I have a server and a client application where the client sends a bunch of packets to the server. The protocol used is UDP. The client application spawns a new thread to send the packets in a loop. The server application also spwans a new thread to wait for packets in a loop.
Both of these applications need to keep the UI updated with the transfer progress. How to properly keep the UI updated has been solved with this question. Basically, both the server and client applications will raise an event (code below) for each loop iteration and both will keep the UI updated with the progress. Something like this:
private void EVENTHANDLER_UpdateTransferProgress(long transferedBytes) {
receivedBytesCount += transferedBytes;
packetCount++;
}
A timer in each application will keep the UI updated with the latest info from receivedBytesCount
and packetCount
.
The client application has no problems at all, everything seems to be working as expected and the UI is updated properly every time a packet is sent. The server is the problematic one...
When the transfer is complete, receivedBytesCount
and packetCount
will not match the total size in bytes sent nor the number of packets the client sent. Each packet is 512 bytes in size by the way. The server application is counting the packets received right after the call from Socket.ReceiveFrom()
is returned. And it seems that for some reason is not receiving all the packets it should.
I know that I'm using UDP which doesn't guarantee the packets will actually arrive at the destination and no retransmission will be performed so there might be some packet loss. But my question is, since I'm actually testing this locally, both the server/client are on the same machine, why exactly is this happening?
If I put a Thread.Sleep(1)
(which seems to translates to a 15ms pause) in the client sending loop, the server will receive all the packets. Since I'm doing this locally, the client is sending packets so fast (without the Sleep()
call) that the server can't keep up. Is this the problem or it may lie somewhere else?