Winsock - 选择侦听套接字上的超时,导致每个后续的Select调用失败

时间:2014-02-13 01:00:29

标签: c++ sockets networking network-programming winsock

我想通过将Select()的超时选项设置为NULL来完全解决我的问题。

但我想使用超时,所以这是我的问题。服务器程序非常简单,它可以监听连接,接受它们并打印到控制台。

问题是在select上第一次超时后,select会返回-1(MSDN给我几乎没有文件说明什么会导致从select()返回-1,只是它是一个错误信号并有效地停止该计划的任何沟通。

服务器 - main.cpp

int main(){

    /* variables */
    int iResult, iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    bool exit=false;
    int foundRoom, tempFoundRoom;
    fd_set readfds, writefds;
    struct timeval tv;
    long double counter=0;
    int maxfd=0;

    /* Server variables */
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL;
    struct addrinfo hints;


    printf("~SERVER~\n");

     /* Initialize Winsock*/
    initialize_winsock(wsaData, hints, &result);

    /* Set socket and bind to TCP listening socket */
    set_socketandbind(ListenSocket, result, maxfd);

    //non-blocking mode
    u_long iMode=1;
    ioctlsocket(ListenSocket,FIONBIO,&iMode);
    ioctlsocket(ClientSocket,FIONBIO,&iMode);

    // clear the set ahead of time
    FD_ZERO(&readfds);
    //FD_ZERO(&writefds);

    //add our descriptors to the set
    FD_SET(ListenSocket, &readfds);

    //wait until either socket has data ready to be recv()d (timeout 5 secs)
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    /* main loop */
    for(;;){
        cout << "Maxfd: " << ListenSocket << " \ " << maxfd << endl;

        //select
        int rv = select(ListenSocket+1, &readfds, NULL, NULL, &tv);

        cout << "Updateing... rv: " << rv << endl;

        if (rv == -1) {
            perror("Select: "); // error occurred in select()
        }else if (rv == 0){
            printf("Timeout occurred! No data after 5 seconds.\n");
        }else{

            // one or both of the descriptors have data
            if (FD_ISSET(ListenSocket, &readfds)) {

                // Accept a client socket
                ClientSocket=accept(ListenSocket, NULL, NULL);

                cout << "Connected a user." << endl;

            }

            counter++;
        }

        cout << endl;
        Sleep(500);

    };

    /* Unset server socket */
    closesocket(ListenSocket);

    system("pause");
    return 0;
}

输出应该是,超时,超时,超时,因为这应该是select()应该如何工作,以及它如何在我的客户端上工作。而输出是超时,错误,错误,错误:

enter image description here

1 个答案:

答案 0 :(得分:4)

每次循环时都需要重置'TV'和FD结构。