Problem:
When functioning as a server, how can we promptly determine when a client disconnects from the connected socket? The common methods for detecting client disconnection when connecting to a server are ineffective in this scenario.
Answer:
Socket connections do not natively provide disconnect events. Therefore, we must periodically check the socket's connection status. The following extension method offers a reliable way to detect if a socket has disconnected:
static class SocketExtensions { public static bool IsConnected(this Socket socket) { try { return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0); } catch (SocketException) { return false; } } }
This method polls the socket at a user-defined frequency to determine connectivity. If polling detects zero bytes available for reading from the socket, the connection is deemed disconnected.
The above is the detailed content of How Can a Server Instantly Detect Client Socket Disconnections?. For more information, please follow other related articles on the PHP Chinese website!