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

标签 c tcp client-server

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

相关文章:

c - 为什么不能将作为输入参数传递给函数的二维数组在其函数声明中声明为 int**?

c++ - 巨大的C文件调试问题

java - Java 中的安全 TCP 连接

c# - 如何在不同的编程语言中使用 C# 方法

sockets - UDP套接字编程中不同语言的客户端和服务器

java - 客户端集群数据库与 Hibernate 同步

c - poll() 在第一次调用后停止设置 POLLIN

c# - 如何修复 "a connection attempt failed because the connected party did not properly respond after a period of time ..."错误?

java - 在本地测试 TCP/IP 连接

c - 在 gcc 中打开优化后标签移动