Thanks Gavin for the response, please see following embedded comments.

On Fri, Feb 24, 2017 at 1:04 PM, Gavin Lambert via Boost-users <boost-users@lists.boost.org> wrote:
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.

That is exactly I am currently doing, if I failed to run  boost::asio::async_write to a specific client, I removed the connection and wait until a new connection from the client is established. Doesn't seem there are other better detecting methods.

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.

Yes, I am also writhe the client program, each client has an unique identification and provides expecting only one connection per client. The client will auto-reconnect to the server if it detect lost connection, the question again, is writing to boost::asio::write the efficient way to detect a stalled connection or  are there any better alternatives to get feedback from the boost::asio::ip::tcp::socket lowest_layer? The problem is the client is always waiting receiving from server, if the client cannot detect from the oost::asio::ip::tcp::socket while waiting on boost::asio::read, then I have to run constantly heartbeat in every second or so which I try to avoid too much unnecessary bandwidth usage as the client is replying on LTE transmission, network bandwidth cost needs be considered.

Thank you.




_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users