gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:49:25 25 4
gpt4 key购买 nike

我在将字符串作为参数传递给我的客户时遇到问题,我是 C 的新手,所以无法真正弄清楚发生了什么。我设法将一个字符传递给服务器,但遇到了字符串问题。此代码表示来 self 的服务器的主循环:

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

服务器打印的信息如下:

enter image description here

谁能帮我一下。

谢谢

最佳答案

您的缓冲区 ch[] 不是空终止的。而且因为您一次只读取 1 个字节,所以该缓冲区的其余部分是垃圾字符。此外,您正在将 &ch 传递给读取调用,但数组已经是指针,因此 &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
}

关于C语言。 TCP 服务器-客户端,字符串传递错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com