0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.