zhangdi zhangdi - 8 months ago 31
C Question

How to keep the server on?

In c, how do I keep the server on when I close the client? (assume the server only handles 1 client at a time ).

I did something like this:

server.c

while(1)
{
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
while ((strcmp(buffer, "quit\n") != 0)
{
.....
}
close(newsockfd);
}


my idea is, when the client receives the "quit" command, it sends it to the server, and when the server gets it, the second loop breaks. And it waits for the next client. My first connection works fine, but the second connection does not work. Can someone explain why? Or is there a better way to do that?

Specific examples would be better. Thanks in advance.

Answer Source

(okay, the comments have gone on too long...)

Clear buffer before the inner while loop:

// ... setup, including bind listen ...
while(1)
{
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
    buffer[0] = 0; /* very important so we don't see data from previous clients */
    while ((strcmp(buffer, "quit\n") != 0)
    {
        .....
    }
    close(newsockfd);
}
// ... shutdown, including close(sockfd)