I am having an application which established a socket connection on a port number 5005 with another device(hardware device with a web server).
Now if my hardware device disconnects then i loose connection with the device.
-
Does this mean that the socket i was
using until now becomes invalid. -
Do i get any special message like
null character or something when
this disconnect happens. - If the socket connection i was
having became invalid then why
doesnt the recv() socket function
throw and SOCKET_ERROR. Instead
why do i receive data of 0
length.
Thanks
When
recvreturns a value of 0 that means the connection has been closed.See the
recvman page:In answer to question #1, yes the socket is now invalid. You must create a new socket and connection for further communications.
Edit
Now as valdo pointed out below, there is also the possibility of having a half-closed TCP connection in which you can’t receive any more but you can keep writing to the socket until you’ve finished sending your data. See this article for more details: TCP Half-Close. It doesn’t sound like you have this situation though.
In answer to question #2, there are basically two ways to detect a closed socket. This assumes that the socket went through an orderly shutdown, meaning the peer called either
shutdownorclose.The first method is to read from the socket in which case you get a return value of 0. The other method is to write to the socket, which will cause the SIG_PIPE signal to be thrown indicating a broken pipe.
In order to avoid the signal, you can set the
MSG_NOSIGNALsocket option in which casesendwould return -1 and seterrnotoEPIPE.