C语言。 TCP server-client,字符串传递错误

时间:2013-03-14 01:51:24

标签: 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(client_sockfd, &ch, 1);
    break;
}

客户端代码:

 char ch[256] = "Test";

 rc = write(sockfd, &ch, 1);

服务器打印的消息如下:

enter image description here

有人可以帮我一把。

谢谢

1 个答案:

答案 0 :(得分:2)

您的缓冲区ch []未终止。并且因为您一次只读取1个字节,所以该缓冲区的其余部分是垃圾字符。此外,您正在使用pass& 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
}