Detection of unexpected disconnection of the connector

This is not a question of how to do this, but a question of whether this is what I am doing wrong. I read that it is impossible to detect if the socket is unexpectedly closed (for example, kill the server / client process, pull the network cable), waiting for data (BeginReceive), without using timers or ordinary sent messages, etc. But quite a while ago, I used the following setting for this, and so far it has always worked perfectly.

public void OnReceive(IAsyncResult result)
{
    try
    {
        var bytesReceived = this.Socket.EndReceive(result);

        if (bytesReceived <= 0)
        {
            // normal disconnect
            return;
        }

        // ...

        this.Socket.BeginReceive...;
    }
    catch // SocketException
    {
        // abnormal disconnect
    }
}

Now, since I read this not so easily, I am wondering if something is wrong with my method. Here? Or is there a difference between killing processes and pulling cables and the like?

+5
source share
1 answer

It is entirely possible and OK to do this. General idea:

EndReceive -, , .

EndReceive , . , , , . , , , , .

EndReceive throws, ( , , ..).

, :

  • EndReceive ( ).
  • , SocketException.
  • , , BeginReceive; - BeginReceive EndReceive ( ). , .
+12

All Articles