1

我正在构建一个可以从服务器和用户(stdin)接收信息的客户端,所以我使用 select 来监控两者。发生的情况是键盘输入被监控,我向客户端发送消息并返回,没问题。但是当服务器发送消息时没有任何反应,我不知道为什么。是否使用select()正确的方法来做到这一点?

这是我的代码:

void readSocket(fd_set tempfd) {
    const char * tweet, * inMessage;
    if (FD_ISSET(srverfd,&tempfd)) {
        inMessage = getMessage();
        printSystemMessages(inMessage);
    }

    if (FD_ISSET(STDIN_FILENO,&tempfd)) {
        tweet = getUserTweet();
        sendMessage(tweet);
        inMessage = getMessage();
        if (strcmp(inMessage,OK) != 0) {
            printSystemMessages(inMessage);
        }
        if (strcmp(inMessage,EXIT) == 0) {
            return;
        }
    }
    return;
}

int main (int argc, char *argv[] ){
    int value;
    bool clientON = false;
    fd_set tempfd;

    if(establishConnection(argv[2],argv[3])){
        cerr << "usage: failed to make connection" << endl << "exiting..." << endl;
        exit(EXIT_FAILURE);
    }

    cout << "Connected successfully" << endl;
    sendMessage("CONNECT "+clientName); //Connect
    if(strcmp(getMessage(),OK) == 0){
        build_select_list();
        printSystemMessages("Welcome!");
        clientON = true;
        cout<< man <<endl;
    }
    while(clientON){
        tempfd = inputFdSet;
        printTweetFormat("TweetMy:");

        value = select(maxSock, &tempfd, NULL, NULL, NULL);
        if (value < 0) {
            perror("select");
            exit(EXIT_FAILURE);
        }
        if (value == 0) {
            continue;
        }
        else {
            readSocket(tempfd);
        }
    }
    close(srverfd);

    return 0;
}
4

1 回答 1

1

这可能会对您有所帮助 - 将 maxSock+1 而不是 maxSock 传递给您的 select() 调用;

从 select() 的手册页中

     nfds  is the highest-numbered file descriptor in any of the three sets,
      plus 1.
于 2012-06-16T10:57:57.160 回答