Frederico Prado

Detecting a remote disconnection on a TCP socket

Discussion created by Frederico Prado on Apr 14, 2010
Latest reply on Apr 21, 2015 by martinpi

Hello.

 

I'm starting to use MQX and I am at a loss about the procedure to detect a remote disconnection once  a TCP link has been established.

 

As far as I understood you can establish a connection by either actively calling connect(), or by calling listen() then accept(), once the connection has been established anytime a data packet arrives addressed to that socket it can be detected by pooling RTCS_selectall(0).

 

My problem is that I haven't found a way to identify when these events are generated by a remote disconnection or by data arriving.

 

Here is the code snippet of my current procedure:

 

 

for (;;) {   sock = RTCS_selectall(0);   if (sock == listensock) {      // Connection requested; accept it.       rlen = sizeof(raddr);      tsock = accept(listensock, &raddr, &rlen);      if (tsock == RTCS_SOCKET_ERROR) {          printf("\naccept() failed, error 0x%lx",                  RTCS_geterror(listensock));          continue;      }   }   else if (sock == tsock) {      // Sends back a message and increments message index      recv(tsock, buffer, 256, 0);      send(tsock, Msg[index], strlen(Quotes[index]) + 1, 0);      index++;   }}

Once I remotely disconnect tsock, it keeps returning as a result of RTCS_selectall(0), but as I am unable to identify this is not an incoming message I keep executing the recv/send routine unaware that the socket is broken by the remote peer.

 

I would like to both know the correct procedure to detect such a disconnection as well as the correct procedure to close the socket gracefully in this case.

 

Thank you in advance,

 

Frederico



 

 

Outcomes