I'm wondering if in my Async Sockets in c#, receiving 0 bytes in the EndRead call means the server has actually disconnected us?
Many Examples I see suggest that this is the case, but I'm receiving disconnects a lot more frequent that I would be expecting.
Is this code correct? Or does endResult <= 0 not really mean anything about the connection state?
private void socket_EndRead(IAsyncResult asyncResult)
{
//Get the socket from the result state
Socket socket = asyncResult.AsyncState as Socket;
//End the read
int endResult = Socket.EndRead(asyncResult);
if (endResult > 0)
{
//Do something with the data here
}
else
{
//Server closed connection?
}
}
From the docs:
If the remote host shuts down the Socket connection and all available data has been received, the EndRead method completes immediately and returns zero bytes.
So yes, zero bytes indicates a remote close.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With