Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I am developing a client server application on windows.
I am using winsock api.

Is ther any function by which i can check the status of the socket connection.

flow of my program is like.



1 ) Establish a connection to the server
2 ) Do something with the socket
3 ) Keep idle
4 ) Send something to the server.

While sending any data to server in 4th step, is ther any way for me to check whether the connection is still alive ?
Posted
Comments
michaelmel 3-Oct-12 20:10pm    
Generally, in your 4th step, if the connection is not alive, your send() will return an error. Generally, your connection can remain active indefinitely, even if idle.
PrafullaVedante 4-Oct-12 2:16am    
ammm ... is ther any way if i just want to check the status of the connection.

If i use return code of send , i will need to send something each time to check connection's aliveness.. :(
michaelmel 4-Oct-12 20:26pm    
If you opened socket with a keep-alive option, TCP will automatically send a heartbeat message to monitor the connection and close it if it is not alive. From memory, keep-alive is default option with Winsock and most UNIX/Linux implementations.

The other option which I use a fair bit is to send my own hearbeat packet into connection (both ways). This also has the advantage that intermediate devices such as routers don't try to be too smart and drop the connection as inactive - as it always has some (small) traffic.

1 solution

Ok, I will just sum it all up and add one more option:

1) Generally, in your 4th step, if the connection is not alive, your send() will return an error. (Note: your connection can remain active indefinitely, even if you send no traffic into it).

2) If you've opened the socket with a keep-alive option, TCP will automatically send a heartbeat message to monitor the connection and close it if it is not alive. From memory, keep-alive is a default option with Winsock and most UNIX/Linux implementations.

3) The other option which I use a fair bit is to send my own hearbeat packet into connection (both ways). This also has the advantage that intermediate devices such as routers don't try to be too smart and drop the connection as inactive - as it always has some (small) traffic.

4) And finally, to check for connection being alive, you can use recv with MSG_PEEK option, something like:
char data;
recv(socket,&data,1, MSG_PEEK);//read one byte

but make sure you are in non-blocking mode. (Note - using PEEK makes sure that the received data is not de-queued and can be read/processed by proper receive routine). This is the method used by Ulimiate TCP/IP.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900