2012-06-13 61 views
0

我跟着this很好的教程來創建一個簡單的非阻塞服務器使用select()函數。下面是我有:服務器不響應新客戶端使用select(),cpp

void setNonBlocking(int socketFD) { 
    int x; 
    x = fcntl(socketFD,F_GETFL,0); 
    fcntl(socketFD,F_SETFL,x | O_NONBLOCK); 
    return; 
} 

int initialize(char * port) { 
    int yes = 1; 
    listener = socket(PF_INET,SOCK_STREAM, 0); 
    if (listener < 0) { 
     perror("listener"); 
     exit(EXIT_FAILURE); 
    } 
    if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { 
     perror("setsockopt"); 
     exit(EXIT_FAILURE); 
    } 
    setNonBlocking(listener); 

    struct sockaddr_in server_address; 
    memset((char *) &server_address, 0, sizeof(server_address)); 
    server_address.sin_family = AF_INET; 
// server_address.sin_addr.s_addr = htonl(INADDR_ANY); 
    inet_aton("132.65.151.39",&(server_address.sin_addr)); 
    server_address.sin_port = htons(atoi(port)); 

    if (bind(listener, (struct sockaddr *) &server_address, 
      sizeof(server_address)) < 0) { 
     perror("bind"); 
     close(listener); 
     exit(EXIT_FAILURE); 
    } 

    listen(listener,BACKLOG); 
    maxSocket = listener; 
    memset((char *) &clientQueue, 0, sizeof(clientQueue)); 

    return 0; 
} 

void readSockets() { 
    int i; 
     cout << "in readSockets()" << endl; 
    if (FD_ISSET(listener,&sockets)) 
     createConnection(); 

    for (i = 0; i < 5; i++) { 
     if (FD_ISSET(clientQueue[i],&sockets)) 
      readData(i); 
    } /* for (all entries in queue) */ 
} 

int main(int argc, char* argv[]) { 
    if (argc != 2) { 
     fprintf(stderr,"usage: server port\n"); 
     exit(EXIT_FAILURE); 
    } 

    if (initialize(argv[1]) != 0) { 
     exit(EXIT_FAILURE); 
    } 

    struct timeval timeout; 
    int value; 

    printf("server: waiting for connections...\n"); 
    while(1) { // main accept() loop 
     build_select_list(); 
     timeout.tv_sec = 1; 
     timeout.tv_usec = 0; 
     value = select(maxSocket, &sockets, (fd_set *) 0,(fd_set *) 0, &timeout); 
     if (value == -1) { 
      perror("select"); 
      exit(EXIT_FAILURE); 
     } 
     if (value == 0) { 
      printf("%d",value); 
      fflush(stdout); 
     } else{ 
      cout << "Value is " << value << endl; 
      readSockets(); 
     } 
    } 
    return EXIT_SUCCESS; 
} 

我的問題很簡單 - 選擇總是返回0,這意味着它不會獲取或不以一個新的連接作出迴應。我前一天用一個更簡單的阻塞服務器檢查了我的客戶端,它確實有效,所以我不認爲它是它的標誌。

你會發現,我想這兩個IP地址:

server_address.sin_family = AF_INET; 
// server_address.sin_addr.s_addr = htonl(INADDR_ANY); 

任何人都可以幫我嗎?我覺得失去了:)

回答

1

請參考man select,第一個參數應該是最高的描述符+ 1的數,所以你的情況:

value = select(maxSocket + 1, &sockets, (fd_set *) 0,(fd_set *) 0, &timeout); 
相關問題