请教下:用API函数做socker时,recv这个函数,在已经读完数据时,一直等在那里,怎么办。那句语句就一直在那执行,下面的语句都不执行了,退都退不出来了,直到连接的另一端断开连接为止,才执行下面的。我看MSDN帮助中的RECV函数发现他就有这点:If no incoming data is available at the socket, the recv call blocks and waits for data to arrive according to the blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK。不知道大家有没有办法,能让他停止这种等待状态,或者说有什么方法在recv之前能检测下数据是否已经接收完了,然后就不调用recv函数了

解决方案 »

  1.   

    设置阻塞套接字的超时时间即可.
    int nMs = 1000;//等待1秒
    setsockopt(m_sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&nMs,sizeof(int));
    到达超时时间,阻塞调用就返回了.你可以在返回后处理其他操作后再次调用该阻塞操作模拟异步.
      

  2.   

    请参考winsock的IO方法~
    select
    WSAAsyncSelect 
    WSAEventSelect
    重叠端口及完成端口当使用SO_RCVTIMEO选项时,每个recv都会在指定的时间内返回.
    下面给出一个简单的select的例子:timeval tm;
    tm.tv_usec = 1000000; //1秒
    tm.tv_sec = 1;  //1秒
    fd_set fd;
    FD_ZERO(&fd);
    FD_SET(s,&fd);
    int i=select(0,&fd,0,0,&tm);  //函数将在2秒后返回
    switch(i)
    {
    case 0:    //超时
      break;
    case SOCKET_ERROR:  //错误
      break;
    default:   //成功
      i=recv(s,buf,sizeof(buf),0);  //不会阻塞
      //数据处理
    }