2012-11-08 172 views
0

我想寫一個多客戶套接字程序,
但是當accept階段我得到Bad文件描述符。
我該如何糾正我的代碼?謝謝!
套接字壞文件描述符

這裏是我的代碼
http://codepad.org/q0N1jTgz
謝謝!
這是我的部分代碼!

while(1) 
{ 
    struct sockaddr_in client_addr; 
    int addrlen = sizeof(client_addr); 

    /*Accept*/ 
    if(clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen) < 0) 
    { 
     perror("Accpet Error"); 
     close(sockfd); 
     exit(-1); 
    } 

    /*Fork process*/ 
    if(child = fork() < 0) 
    { 
     perror("Fork Error"); 
     close(sockfd); 
     exit(-1); 
    } 
    else if(child == 0) 
    { 
     int my_client = clientfd; 
     close(sockfd); 

     send(my_client, welcome, sizeof(welcome), 0); 

     while ((res = recv(my_client, buffer1, sizeof(buffer1), 0)) > 0) 
     { 
      string command(buffer1); 
      cout << "receive from client:" << command << ", " << res << " bytes\n"; 
      memset(buffer1, '\0', sizeof(buffer1));  
     } 
    } 

    close(clientfd); 

} 
+0

通過[編輯它(http://stackoverflow.com/posts/13287359/edit)請在你的問題你的代碼的相關部分。鍵盤將隨時消失。 – 2012-11-08 10:59:21

回答

1

有代碼中的一些錯誤 首先你需要周圍使用分配括號childclientfd

68應改爲

if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen)) < 0) 

和線76應該

if((child = fork()) < 0) 

還必須從既然你已經關閉了監聽套接字分叉過程returnexit()

行之後所以加exit(0);return 0;94

我強烈建議你啓用了警告編譯代碼,以便及早發現的分配問題。 e.g使用-Wall-Wextra標誌,如果你正在使用gccg++

+0

非常感謝你,這對我非常有用,我會糾正我的代碼並重試它。謝謝!!!!!!!!!! – Andy

+0

現在,該程序工作完美,但還有一個問題是,clientfd始終是一個相同的號碼,服務器無法識別究竟哪個客戶端發送消息,我該如何解決它?謝謝! – Andy

+0

@ ChengChung-Hao唯一區分客戶端的是他們的IP地址:端口,您可以通過getpeername()從套接字FD獲取端口。 – EJP

相關問題