C# Socket.receive continuously receives 0 bytes and does not block in the loop C# Socket.receive continuously receives 0 bytes and does not block in the loop multithreading multithreading

C# Socket.receive continuously receives 0 bytes and does not block in the loop


If you received 0 bytes, that usually means the sender has closed their send socket. In a Socket, the send and receive channels are separate; I expect what is happening is that your send (their receive) is still open and available, hence clientSocket.Connected returning true (you can still send them a reply), but: they closed their send (your receive) as soon as they sent their payload (this is common, to indicate the end of a batch). Basically, you just need to detect the 0-byte receive, and treat that as the end: no more data will ever be incoming once you have had a non-positive reply from receive. So just write any response you need to write (they can still be listening, even though they will never speak again), and shutdown the socket.

As a side note: in HTTP/1.1 with Connection: keep-alive, the can keep their socket open ready to send the next request - but it just looks like in this case, they simply didn't. They closed their socket immediately after issuing the request. Which is fine. Just serve the response and close the socket completely. No more requests will be incoming.