Detecting a remote disconnection on a TCP socket

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

Detecting a remote disconnection on a TCP socket

2,115 次查看
FredericoPrado
Contributor II

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



 

 

标签 (1)
标记 (1)
0 项奖励
4 回复数

856 次查看
CompilerGuru
NXP Employee
NXP Employee

I don't know MQX, but typically with socket programming a closed connection is signaled by recv returning 0 as number of bytes read. There is usually also no guarantee of how many bytes were read in a single recv, it may return with fewer than the passed in buffer size.

 

Daniel

0 项奖励

856 次查看
martinpi
Contributor III


If this is true, how do I distinguish between a closed connection and a connection that is still open but no new data arrived?

0 项奖励

856 次查看
Martin_
NXP Employee
NXP Employee

Typically in an RTOS system the recv() call is blocking, so if the connection is established and no new data arrived, the task is just blocked in the recv() call.

In RTCS, recv() returns -1 (RTCS_ERROR) when remote peer disconnects (sends FIN to us). The socket error code is set to RTCSERR_TCP_CONN_CLOSING and you can read it from the socket by RTCS_geterror().

Martin

0 项奖励

856 次查看
martinpi
Contributor III

From Martin to Martin:

Thanks a lot! :smileyhappy:

0 项奖励