2012-06-16 194 views
1

我正在构建一个客户端,可以从服务器和用户接收信息(stdin),所以我使用select来监视两者。会发生什么是一个键盘输入被监控,我发送消息给客户端,并得到一个回来,没有问题。但是当服务器发送消息时什么也没有发生,我不知道为什么。正在使用select()这样做的正确方法?C++:使用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; 
} 
+1

可以参考http://beej.us/guide/bgnet/对于选择使用。 – CuriousSid

+0

你有2个以上的主要功能 - 你可以真正清理这件事,使事情更清晰,然后更有可能得到答案 – mathematician1975

+0

@curiousbill - 我读了几次,找不到答案。 – yotamoo

回答

1

这可以帮助你 - 通过maxSock + 1,而不是maxSock您选择()调用;

从man页面上选择()

 nfds is the highest-numbered file descriptor in any of the three sets, 
     plus 1. 
+0

这是一个很好的观点。然而,由于'maxSock'没有在这个代码片段中的任何地方定义,所以你永远无法知道它是否已经包含'+ 1' :) –

+0

@EitanT - 的确 - 这就是为什么我说“This * might * help” :) – mathematician1975