C语言。TCP服务器客户端,字符串传递错误

C语言。TCP服务器客户端,字符串传递错误,c,tcp,client-server,C,Tcp,Client Server,我在将字符串作为参数传递给我的客户机时遇到了一个问题,而且我是C新手,因此无法真正了解到底发生了什么。我设法向服务器传递了一个字符,但字符串出现了问题。此代码表示来自我的服务器的主循环: while(1) { char ch[256]; printf("server waiting\n"); rc = read(client_sockfd, &ch, 1); printf("The message is: %s\n", ch); write(c

我在将字符串作为参数传递给我的客户机时遇到了一个问题,而且我是C新手,因此无法真正了解到底发生了什么。我设法向服务器传递了一个字符,但字符串出现了问题。此代码表示来自我的服务器的主循环:

while(1)
{
    char ch[256];
    printf("server waiting\n");

    rc = read(client_sockfd, &ch, 1); 
    printf("The message is: %s\n", ch);
    write(client_sockfd, &ch, 1);
    break;
}
客户端代码:

 char ch[256] = "Test";

 rc = write(sockfd, &ch, 1);
服务器打印的消息如下所示:

谁能帮我一下吗


谢谢您

您的缓冲区ch[]不是以null结尾的。因为一次只读取1个字节,所以该缓冲区的其余部分是垃圾字符。另外,您正在使用将&ch传递给read调用,但是数组已经是指针了,所以&ch==ch

至少代码需要如下所示:

    rc = read(client_sockfd, ch, 1); 
    if (rc >= 0)
    {
       ch[rc] = '\0';
    }
但这样一次只能打印一个字符,因为一次只能读取一个字节。这样会更好:

while(1)
{
    char buffer[256+1]; // +1 so we can always null terminate the buffer appropriately and safely before printing.
    printf("server waiting\n");

    rc = read(client_sockfd, buffer, 256);
    if (rc <= 0)
    {
        break; // error or remote socket closed
    }
    buffer[rc] = '\0';

    printf("The message is: %s\n", buffer); // this should print the buffer just fine
    write(client_sockfd, buffer, rc); // echo back exactly the message that was just received

    break; // If you remove this line, the code will continue to fetch new bytes and echo them out
}
while(1)
{
字符缓冲区[256+1];//+1,因此在打印之前,我们可以始终为空并安全地终止缓冲区。
printf(“服务器等待\n”);
rc=读取(客户端\u sockfd,缓冲区,256);
if(rc)