0
votes

I have a client-server app where both communicate over tcp. We are planning on reusing the tcp in-built keep alive mechanism to ensure both client and server know the other guy is alive.

A few questions:

  1. Right now, we have done a setsockopt(..) to enable tcp keep alive and also have set the keep alive timeout values. Lets assume the application is idle. I want the application to know that the keep alive timed out ...which means the client-server connection is down. The app then has to display an error page. What is a good way for the application to know that? I believe if a tcp keep alive times out, subsequent attempts to send a msg over that socket will return a WSAENETRESET error, but I want the app to know even if it is idle and no messages are flowing.

I was thinking of doing the following: Have a loop that runs every 20s (duration may be increased/decreased) and does a setsockopt to set the keep alive to true. If the connection is broken, this call will return a WSAENETRESET error.

  1. What would be a good keep alive interval to use?

  2. Any issues with using the tcp in built keep alive mechanism?

Thanks in advance...

2

2 Answers

0
votes

There's nothing special you need to do. Presumably, you are already trying to read from the socket or appropriately waiting for it to become ready to read. If the connection fails, it will be ready to read (since you can no longer wait for it to become ready to read), and your read attempt will get an error.

0
votes

About the way of checking keep alive:

If the program is blocked reading the stream and keep alive fails it will be interrupted with an error. If your program doesn't need to wait for incoming messages you can spawn a thread that does that.

Another question is if you really need to check every 20 seconds or you can just check when you need to send a message.

If find keep alive particularly useful at server side, where the program waits for messages, because otherwise the server would never know that the connection is broken and will be waiting for incoming messages for ever (wasting threads and ports).

About your questions:

  1. Default value is usually 2 hours, these are lightweight packets so you could keep it much lower, but I wouldn't use a value lower than a minute unless it's really necessary.
  2. No that I'm aware of.