Pratik Singhal
Pratik Singhal

Reputation: 6492

Why does the server enter an infinite loop while closing client side connection

I am trying to send data through a Tcp connection using C.

I am able to send data properly , but when I close the client side application (CTRL-C), the loop in the server side runs infinitely.

Can anyone explain me what I am doing wrong ? What can I do to prevent it?

    //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()") ; 
    }
}   

Upvotes: 0

Views: 1602

Answers (1)

glglgl
glglgl

Reputation: 91119

Your server code runs in 2 loops: the outer one waits for more connections, and as soon as you have a connection, it goes on running.

There is currently no reason to terminate one of them. If you want to terminate the inner one, you should additionally check for the result value being == 0, meaning the end of the connection.

Even if you do

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);
}

your outer loop goes on running.

Upvotes: 3

Related Questions