Ido Hadar
Ido Hadar

Reputation: 187

How to check if connection lost

How can I check if my connection with the server lost ? (Client or Server side no matter) I'm using TCP connection, and the server recv unlimit clients. for each client the server create thread. and with that's way I can recv / send for each client.

Upvotes: 4

Views: 5880

Answers (4)

selbie
selbie

Reputation: 104464

You could consider using the TCP-keepalive option on the socket as one option.

But many NATs and statefull firewalls will actually drop TCP connections if it observes no activity within a certain period of time.. And this activity timeout may be faster than the periodic keepalive message supported by TCP. For this reason, a protocol message to your server every 30-60 seconds is usually enough to keep the connection "alive" with regards to NATs.

My personal take is this. It's the responsibility of the client to inform the server that "I'm still here" if the connection is meant to be long running. The server should periodically wake up and close any TCP connection that hasn't had any traffic on it the last N seconds. (Where N is a reasonable value for your application). In your case, the "thread per client" approach means each thread just needs to decide when a remote client has become unresponsive.

Within the protocol, the client can send it's own custom "ping" message to the server every 30-60 seconds. The server always acks this message back and records that the client is still around.

A lot of what I'm discussing really depends on your protocol, what your service does, and how long the connections are expected to last.

Upvotes: 4

Davide Berra
Davide Berra

Reputation: 6568

If a socket is not connected anymore, send() returns SOCKET_ERROR and WSAGetLastError() returns WSAENOTCONN or other related error.

If you are reading data and recv() returns zero, then the peer has performed an orderly shutdown.

If you are reading from a not connected socket, then recv() returns SOCKET_ERROR and WSAGetLastError() returns WSAENOTCONN or other related error.

WinSock error codes are documented on MSDN.

Upvotes: 0

Steve Townsend
Steve Townsend

Reputation: 54128

Keep a async or sync receive call outstanding at all times (many apps do this anyway by design) - on connection loss, this will complete with failure conditions depending on your specific receive API.

Upvotes: 0

tr0yspradling
tr0yspradling

Reputation: 604

Build a ping system in your application.

Upvotes: 1

Related Questions