0

I am trying to create an asynchronous server in C++ using Boost ASIO library, it goes by standard model provided at their webpage, ioservice and worker (session) I am using something like this:

asio::async_read(socket,buffer(data,datalen),[=]( error , len ){
     if(error || len==0) disconnect(); else processRequest(data,len);
})

Firstly, it works just fine, when user opens and closes connection - OS does the job.

But problem comes when user disconnects from internet by force, socket remains in "ESTABLISHED" state, though user is already gone, yeah, how would OS handle sending TCP close packet, when internet is not available anymore?

Also problem comes with telephony internet networks, user travels, switches zone from HSDPA to no internet and finally GPRS, old HSDPA socket remains "ESTABLISHED", though user already doesn't use it.

How to detect dead connections like this?

Tanner Sansbury
  • 51,153
  • 9
  • 112
  • 169
  • 1
    There's a keep-alive mechanism defined with the TCP/IP protocol, that enables to detect such loss of transport layer. [See here](http://stackoverflow.com/questions/20188718/configuring-tcp-keep-alive-with-boostasio) also please. – πάντα ῥεῖ May 03 '15 at 08:59

1 Answers1

2
  • When the client application closes the socket your read handler will be called immediately
  • When the client application crashes but the client OS is still online your read handler will be called after the client OS timeout (one minute or so)
  • When the client computers cable is unplugged there is no notification at all. You can implement a keep alive mechanism at application layer or use the TCP built-in keep-alive. I'd recommend to do your own as you have more control (e.g. reconnect a session). In principal you do an async_write which would result in your write handler being called with an error.
stefan
  • 3,681
  • 15
  • 25
  • Can I actuallly send 0 bytes of data through TCP to client, so client won't notice it in recv and I will make a probe check if connection is alive? I don't want to bother client implementation with handling some ping packet. –  May 05 '15 at 18:38
  • You cannot send 0 bytes. For a keep alive at application layer there must be an agreed protocol between client and server. the client should have the same problem as the server. if the client is not interested in keep alive you could simply implement a timeout on the server side and kick the client. – stefan May 05 '15 at 19:12
  • For a keep alive (ethernet cable physically removed) - if the code decides the connection has been lost and i restart the client to try and re-connect to the server - when the cable is plugged back in the connection oscillates - like its not performing the connect handshake correctly - how would i go about re-establishing the connection having reset it client side? I cannot change the server unfortunately. Im trying to report to the user when the connection is down including no physical connection. – Danaldo Dec 14 '22 at 17:36