0

I was wondering if there is any way to notify a server if a client side application was closed. Normally, if I Ctrl+C my client side terminal an EOF-signal is sent to the server side. The server side async_read function has a handle which has boost::system::error_code ec argument fed into it. The handle is called when the server side receives EOF-signal which I can happily process and tell the server to start listening again.

However, if I try to cleanly close my client application using socket.shutdown() and socket.close() nothing happens and the server side socket remains open.

I was wondering, is there a way to somehow send an error signal to the server-side socket so I could then process it using the error code?

Tanner Sansbury
  • 51,153
  • 9
  • 112
  • 169
MutomboDikey
  • 155
  • 2
  • 12
  • 1
    If your read handler gets called with bytes_read = 0, that usually means that the connection received `RST` or channel close (in TCP). You could do something based on this. – Arunmu Aug 23 '16 at 13:51
  • 1
    the destructor of asio::ip::tcp::socket implicitly calls shutdown() followed by close(). Your server will certainly receive an EOF error if you shutdown the client end. something else is wrong. – Richard Hodges Aug 23 '16 at 13:52
  • ah yes - that's it. async_read_some can return success with a zero-byte read. This indicates an EOF condition. – Richard Hodges Aug 23 '16 at 13:52
  • That one was a bit tricky. It appears I made a mistake when writing unit tests and EOF signal is indeed generated when I gracefully terminate the application. However, I was led into confusion by forceful termination of the program, which, expectedly, just like pointed out in the answer below, will not notify the server of anything. In this case "ping" feature is necessary. – MutomboDikey Aug 23 '16 at 16:41

1 Answers1

2

The approaches described in comments covers 99% of cases. It doesn't work when client machine was (not gracefully) turned off, or network problems.

To get reliable notification of disconnected client you need to implement "ping" feature: to send ping packets regularly and to check that you received pong packets.

Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
  • Yes, that was also one of my concerns, that is, the fact that if someone simply forcefully turns off the computer the server will not be notified unless I implement the ping feature, just like you said. As for the rest, comments to save the day. – MutomboDikey Aug 23 '16 at 16:39
  • wouldn't keepalive handle that ? – Arunmu Aug 24 '16 at 07:24
  • @AndyT Cool. I didn't know that. +1 – Arunmu Aug 24 '16 at 11:00