I have a asynchronous TCP/IP client using asio. When the connection is lost, my handle function of async_read recieve an error. So I'm informed that a connection is lost.Now, I'm refactoring some legacy codes implementing a synchronous TCP/IP client where the abstract interface enforces this sequence:a synchronous write, then a synchronous read.Doing that with asio is fairly easy, but I would like to know asynchronously if the connection is lost.Is there a more elegant way than:Option A:Add a thread that checks if the socket is still alive (by trying to read... but how can I be sure that the read doesn't steal data from my synchronous read ? See Boost asio ip tcp iostream Error Detection)Option B:Use async_read instead and and emulate a synchronous read
I think the answer is no. Maybe there are some platform specific solutions though.
I don't think the TCP protocol can detect a connection failure unless it fails to receive an acknowledgement to sent packets within a certain time frame.
I've implemented option B. But, there are 2 things I don't understand 1. disconnections are not detected and 2. If I unplugged the ethernet cable of the server (that is a printer), I can still send it data and it returns no error. Only the second time, it will throw an error
Worth mentioning; there are some limitations to TCP-keepalive, most notably there is no portable way (to my knowledge) to set the timeout of the keepalive. Also, the default timeouts are quite large; for example, on Linux, the default keepalive interval is 2 hours, and 9 probes must fail before the connection is deemed dead.
The essence is, in most cases, you must resort to dealing with connection timeout yourself in your application-code, adding "heartbeat"-checks to the protocol if possible, and trying to figure sane defaults for timeouts. ("Should this operation really ever take 5 seconds?", etc.")