您的缓冲区 ch[] 不是以空值结尾的。而且因为您一次只读取 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
}