2013-03-14 73 views
1

我有一个将字符串作为参数传递给我的客户端的问题,而我对C来说是新的,因此无法真正弄清楚发生了什么。我设法将一个角色传递给服务器,但遇到了字符串问题。这个代码表示从我的服务器主循环:C语言。 TCP服务器客户端,字符串传递错误

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

能有人给我用这个手。

谢谢

回答

2

您的缓冲区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 
}