Instantly detect client disconnection from server socket

后端 未结 14 1625
北恋
北恋 2020-11-22 09:27

How can I detect that a client has disconnected from my server?

I have the following code in my AcceptCallBack method

static Socket hand         


        
14条回答
  •  一个人的身影
    2020-11-22 10:04

    I've found quite useful, another workaround for that!

    If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive - EndReceive methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available - even though BeginReceive is triggered, its value will be zero) or Socket.Connected value becomes false in this call (don't try to use EndReceive then).

    I'm posting the function I used, I think you can see what I meant from it better:


    private void OnRecieve(IAsyncResult parameter) 
    {
        Socket sock = (Socket)parameter.AsyncState;
        if(!sock.Connected || sock.Available == 0)
        {
            // Connection is terminated, either by force or willingly
            return;
        }
    
        sock.EndReceive(parameter);
        sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);
    
        // To handle further commands sent by client.
        // "..." zones might change in your code.
    }
    

提交回复
热议问题