【问题标题】:C language. TCP server-client, string passing errorC语言。 TCP 服务器-客户端,字符串传递错误
【发布时间】:2013-03-14 01:51:24
【问题描述】:

我在将字符串作为参数传递给我的客户时遇到问题,而且我是 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);

服务器打印的信息如下:

谁能帮帮我。

谢谢

【问题讨论】:

    标签: c tcp client-server


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 2021-08-23
      • 2015-05-06
      • 2013-08-24
      • 2012-10-05
      • 1970-01-01
      • 2015-12-01
      • 2020-09-13
      • 1970-01-01
      相关资源
      最近更新 更多