C套接字编程:单个服务器多个客户端

时间:2015-12-09 04:01:21

标签: c socketserver

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

当客户端断开连接时,服务器会重复客户端发送的最后一条消息。如何修改它以使其不再重新打印客户端的消息?非常感谢你提前

1 个答案:

答案 0 :(得分:0)

检查valread == -1。您忽略该情况,在数组开头之前写入,然后输出上一个请求。一种简单的方法是将== 0更改为<= 0