Instantly detect client disconnection from server socket

后端 未结 14 1696
北恋
北恋 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 09:43

    The example code here http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx shows how to determine whether the Socket is still connected without sending any data.

    If you called Socket.BeginReceive() on the server program and then the client closed the connection "gracefully", your receive callback will be called and EndReceive() will return 0 bytes. These 0 bytes mean that the client "may" have disconnected. You can then use the technique shown in the MSDN example code to determine for sure whether the connection was closed.

提交回复
热议问题