On 23/02/2017 23:09, jupiter via Boost-users wrote:
I have a server socket connected by many clients using boost::asio::ip::tcp::socket to set up server socket connection and to use boost::asio::ip::tcp::acceptor async_accept for new client connections. The client may come and go, so I need to check if the connection is still valid or not before sending message to clients. How can I check if a client connection is no longer valid? My server does not seem get any indication when a client terminate the connection.
There are a few platform-specific sockopts that sometimes do the trick, but generally the simplest way to test whether a connection is still alive is to try to transmit something -- if the connection is lost it will then either immediately or after a timeout fail with a "connection reset" error. You usually can't detect a disconnection if you're just waiting for a read without sending anything. Also, if clients have some means of identification or authentication (using the IP is possible but not really recommended due to gatewaying or multiple separate applications), and provided you're expecting only one connection per client, then you could treat a reconnection from the same client as a disconnection of their previous connection. If clients auto-reconnect this would probably be the fastest method of identifying a lost connection, but it can be tricky to avoid causing problems if not implemented carefully.