以下是服务端的Select部队,我在客户端发送一个字符串“hellow”,然后客户端退出,为什么在服务器端一直循环显示“hellow”。我不明白为什么执行过一次recv之后,FD_ISSET()还会有效,也就是说为什么hConnected还处于有数据接收的状态(而此时客户端已退出)?
其中,hConnected是一个已连接的SOCKET。while(1)
{
fd_set fd;
FD_ZERO(&fd);
FD_SET(hConnected, &fd);
nRet = select(0, &fd, NULL, NULL, NULL);
if(FD_ISSET(hConnected, &fd))
{
char buf[30];
int nBytes = recv(hConnected, buf, 30, 0);
buf[nBytes] = '\0';
cout << buf << endl;
}
}

解决方案 »

  1.   

    当网络异常时recv会返回一个SOCKET_ERROR,但是楼主没有进行错误判断,正确的应当是(当然写法上就自己去设计)
    while(1)
    {
    fd_set fd;
    FD_ZERO(&fd);
    FD_SET(hConnected, &fd);
    nRet = select(0, &fd, NULL, NULL, NULL);
    if(FD_ISSET(hConnected, &fd))
    {
    char buf[30];
    int nBytes = recv(hConnected, buf, 30, 0);
                       if(nBytes==SOCKET_ERROR)
                       {
                          if(WSAEWOULDBLOCK==WSAGetLastError())
                             continue;
                          /*错误处理*/
                          closesocket(hConnected);
                          hConnected=INVALID_SOCKET;
                          break;
                       }
    buf[nBytes] = '\0';
    cout << buf << endl;
    }
    }
      

  2.   

    nRet = select(0, &fd, NULL, NULL, NULL);
    //////////////////////////////////////////////////////
    nRet = select(0, &fd, NULL, NULL, NULL);
    if(nRet==SOCKET_ERROR)
       break;
      

  3.   

    select() 的返回值:This function returns the total number of socket handles that are ready and contained in the fd_set structures, zero if the time limit expired, or the SOCKET_ERROR if an error occurred. If the return value is SOCKET_ERROR, WSAGetLastError can be used to retrieve a specific error code.