如何使用keepalive选项检测死客户端

时间:2013-10-30 06:48:24

标签: sockets tcplistener keep-alive tcpserver setsockopt

正如我在标题中提到的,我使用keepalive选项来检测服务器端的死客户端。在连接的tcp套接字上启用keepalive的代码片段如下所示。其他操纵keepalive行为的选项,如TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL等,默认为系统。

int optval;
socklen_t optlen = sizeof(optval);
if(setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
  perror("setsockopt()");
  close(s);
  exit(EXIT_FAILURE);
}

在服务器端,在连接的套接字上,服务器线程将处于recv调用中,等待客户端向服务器发送命令。这段代码片段看起来像这样。

for(; dwBytesReceived < dwBlockSize; dwBytesReceived += iByteCount) {
retry:
            iByteCount = recv(m_ConnectSocket, ((UX_CHAR *)pBlock + dwBytesReceived), (dwBlockSize - dwBytesReceived), flag);
            if (UX_SUCCESS >= iByteCount) {
                    if (iByteCount == 0) {
                            // Connection from client is unexpectedly closed. Terminate Server instance thread.
                            ret = UX_ECLIENTSHUTDOWN;
                            UX_ERROR("Connection from client is unexpectedly closed. Terminating Server instance thread, errno:%d", UX_ECLIENTSHUTDOWN);
                            goto out;
                    }
                    ret = get_last_sock_error();
                    if (EAGAIN == ret) {
                            UX_ERROR("The socket is marked non-blocking and the requested operation, recv, would block");
                            goto retry;
                    }
                    ret = -errno;
                    goto out;
            }
}

当客户端有序关闭时,recv调用返回0并确保客户端已终止。所以我的问题是当keepalive检测到死客户端时,recv会返回什么?或者它是否为系统错误变量设置了错误,我可以从“get_last_sock_error”中读取它并确保客户端已死。感谢。

1 个答案:

答案 0 :(得分:0)

  

当keepalive检测到死客户端时,recv会返回什么?

-1,errno.

的值合适
  

或是否将错误设置为系统错误变量