输入 "quit" 字符串时服务器程序未结束

Server program not ending when "quit" string entered

我有一个基本的 linux 套接字程序,主要是 运行 它接受来自客户端的字符串并发送到服务器。当输入 "quit" 时,我的客户端程序结束,但服务器端不断地打印出 "quit" 直到你终止程序。要么我没有正确阅读字符串,要么我的逻辑不对。

代码部分...

while (1)
{
    //fetch message from client and write to stdout
    num_client_bytes = recv(client_sockfd, buf, LEN, 0);

    if (-1 == num_client_bytes)
    {
        perror("server-- recv failed");
    }
    else
    {
        printf("client msg: %s", buf);

        if (0 == strcmp(buf, "quit\n"))
        {
            break;
        }

    }
}

//remove local socket file and close sockets
unlink(SOCKET_NAME);
close(client_sockfd);
close(server_sockfd);
return 0;

您需要在 recv

之前 memset buf

recv 不会在从套接字读取的字符串末尾添加 '[=15=]', 您还应该检查 recv 是否读取了整个 4 个字节,然后更改:

strcmp(buf, "quit\n")

strncmp(buf, "quit\n",4)// if you are not sure client sends \n