Search code examples
csocketserver

C socket programming:single server multiple clients


for (i = 0; i < climax; i++) //input output operations from clients
{
    sockfd = client_socket[i];
    if (FD_ISSET( sockfd , &fds))
    {
        if ((valread = read( sockfd , request, 1024)) == 0) //check for disconnection of client
        {
            getpeername(sockfd , (struct sockaddr*)&cliaddr , &length); //obtain details of disconnected client
            printf("Client Disconnected: IP::%s %s , port %d . \n", ipv6client,
                   ipv4client, ntohs(cliaddr.sin_port));
            close( sockfd );
            client_socket[i] = 0; //socket closing and set socket to null to be reused
        } else{
            request[valread] = '\0'; //convert request to string and prepare for parsing

            printf("Request from ::%s %s , port %d: ", ipv6client,
                   ipv4client, ntohs(cliaddr.sin_port));

            printf("%s",request);
        }
    }
}

When a client disconnects, the server repeats the last message the client sent. How can I modify this to make it not reprint the client's message again? thank you so much in advance


Solution

  • Check for valread == -1. You ignore that case, write before the beginning of the array, and then output the previous request. One simple way is to change == 0 to <= 0.