2014-04-10 11 views
0

我試圖通過使用C.爲什麼服務器進入無限循環,同時關閉客戶端連接

我能夠正確地發送數據,但一個TCP連接發送數據時,我關閉客戶端應用程序( CTRL-C),服務器端的循環無限運行。

任何人都可以解釋我做錯了什麼嗎?我能做些什麼來防止它?

//Server-Side code. 
while (TRUE) 
{ 
    accepted_socket = accept(connection_socket, (struct sockaddr*)0, 0) ; 
    if(accepted_socket < 0) 
    { 
     perror("accept function in main() ") ; 
     close(connection_socket) ; 
     exit(1) ; 
    } 
    do 
    { 
     int recieved_bytes = recv(accepted_socket, &buff,1, 0) ; // it will store the recieved characters inside the buff. 
     if(recieved_bytes < 0) 
     { 
      perror("Error occurred ! Recieved bytes less than zero. in mainloop.") ; 
     } 
     printf("%c", buff) ; 
    } 
    while(buff!= ' ') ; // This loop runs infinitely. 

} 


//Client Side-Code 
char c = 'c' ; 
do 
{ 
    c = getchar() ; 
    if(send(*connection_socket, &c, 1, 0) < 1) 
    { 
     if(errno == ECONNRESET) 
     { 
      fprintf(stderr, "Your message couldn't be sent, since connection was reset by the server.\n") ; 
      exit(1) ; 
     } 
     perror("Not all bytes sent in send() in main()") ; 
    } 
} 

回答

3

您的服務器代碼2個循環運行:外一個等待更多的連接,並且只要你有一個連接,它繼續運行。

目前沒有理由終止其中之一。如果要終止內部結果,則還應檢查結果值== 0,這意味着連接結束。

即使你

while (TRUE) 
{ 
    accepted_socket = accept(connection_socket, (struct sockaddr*)0, 0); 
    if (accepted_socket < 0) 
    { 
     perror("accept function in main() "); 
     close(connection_socket); 
     exit(1); 
    } 
    // here starts the loop for the accepted_socket: 
    do 
    { 
     int recieved_bytes = recv(accepted_socket, &buff,1, 0); // it will store the recieved characters inside the buff. 
     if(recieved_bytes < 0) 
     { 
      perror("recv"); 
     } 
     size_t i; 
     for (i=0; i < received_bytes; i++) printf("%c", buff[i]); 
    } while(received_bytes != 0); 
} 

您外環繼續運行。

相關問題