c - 为什么服务器在关闭客户端连接时进入无限循环

标签 c sockets tcp infinite-loop

我正在尝试使用 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()") ; 
    }
}   

最佳答案

您的服务器代码在 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);
}

你的外循环继续运行。

关于c - 为什么服务器在关闭客户端连接时进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22988030/

相关文章:

vb6 - 您如何知道已向 Web 服务器发出 POST 或 GET 的 Winsock 控件何时接收到所有数据?

python-3.x - Python套接字: how to detect and list connected clients in server in the other clients and how to update it when a client disconnected?

互联网 PC 中的 TCP 监听器,我如何将那台 PC 连接到特定的 Ip? C#

c# - 套接字错误 10054 : Error Handling Issue

c++ - c99 : 63 characters of an internal name are significant?

c++ - 在 Windows 中,如何使用 C++ 检查端口是否可用

c++ - socket编程tcp发送文件

c - 函数 main 从子例程接收到不正确的值

c - 无限递归 : binary search & asserts

C - 在 sscanf() 中使用空格