【问题标题】:How to determine whether connection to socket was closed如何确定与套接字的连接是否已关闭
【发布时间】:2011-07-16 01:02:20
【问题描述】:

我在 Linux 下用 C++ 编写套接字。我有个问题。如何确定客户端是否关闭了连接。

特别是在服务器接受客户端并开始等待来自客户端的一些数据的情况下。但客户端不发送任何内容,只是关闭与服务器的连接。在这种情况下,我的服务器一直在等待一些数据。

这是我的程序示例:

 newsockfd = accept(sockfd, 
             (struct sockaddr *) &cli_addr, 
             &clilen);
 if (newsockfd < 0) 
      error("ERROR on accept");
 bzero(buffer,256);
 n = read(newsockfd,buffer,255);

我的服务器上还有几个套接字。我需要知道客户端关闭了哪个套接字。

【问题讨论】:

  • 我不明白“客户端关闭了连接到哪个套接字”?你需要“newsockfd”的值还是????

标签: c++ linux sockets


【解决方案1】:

如果客户端关闭连接,n = read(newsocketfd, buffer, 255) 将返回 0。

【讨论】:

    【解决方案2】:

    您可以使用“setsockopt”将套接字设置为超时。您需要#include sys/socket.hsys/types.h

    int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen); 
    

    您需要 SO_RCVTIMEO 或 SO_SNDTIMEO 作为 optname。对于 optval,您需要一个指向 struct timeval 的指针,并且 level 是 SOL_SOCKET。例如:

    struct timeval tv;
    tv.tv_sec = 10;
    tv.tv_usec = 0;
    
    setsockopt(mySocket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); 
    

    将设置套接字在 10 秒后发送操作超时。

    【讨论】:

    • 超时并不表示客户端关闭了套接字。
    【解决方案3】:

    您想在套接字上使用 select 或 poll,而不仅仅是读取。这样一个慢客户端就不会阻塞整个服务器。

    您还需要跟踪所有套接字。

    我的多套接字服务器的基本伪代码如下所示:

    <create/bind serversocket, listen on it, add it to fd_set>
    
    while ( running )
    {
       nd = select( maxfd, fd_set, null, null, timeout )
       if ( nd == 0 )
          continue;  // timeout - do periodic processing
       if ( fd_isset( fd, serversocket )
       {
           do the accept on the server socket and add new socket to the fd_set
       }
       if ( isset( fd, clientsocket ) )
       {
           now you know data is available on the socket, so you can read from it
           a return of 0 on the socket indicates the socket was closed
           in which case you should close your end and remove socket from fd_set
       }
    }
    

    我省略了很多细节,但这是基本结构。

    【讨论】:

    • 如果按照上面的结构,那么当一个socket上有一个事件(比如被关闭)那么isset(fd,clientsocket)就会为真,读取会返回0(EOF )-顺便说一句,我在代码中特别提到了(您显然没有费心去阅读)。这是一个简单的结构,用于处理一个服务器套接字和多个客户端套接字并对它们上的事件做出反应。
    猜你喜欢
    • 2012-06-13
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2016-08-03
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多