C套接字:回显服务器错误的回复

C sockets: Echo server bad reply

本文关键字:错误 回复 服务器 套接字      更新时间:2023-10-16

我已经读了很多问题,因为我发现,但我仍然有我的问题....

我有一个非常示例的客户端/服务器套接字:

  • 服务器与客户端建立连接完成
  • 从客户端接收消息完成
  • 在服务器端打印消息DONE
  • 从服务器返回消息到客户端问题
  • 在客户端打印服务器应答PROBLEMS

我将消息从客户端发送到服务器没有问题,但是当我发送回消息时,我总是得到奇怪的字符

注意:我将''字符添加到接收的字符串

<标题>客户端代码
//... socket initialization and other code
write(sockfd, msg, strlen(msg));    
printf("Message sent ! n"); 
// Listen for reply
listen(sockfd, 5);
struct_size = sizeof(con_addr);
serverfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size);
// Read message
bytes_read = read(serverfd, server_reply, 100);
server_reply[bytes_read] = '';
printf("Server response: %s n", server_reply);
// Close socket
close(sockfd);
close(serverfd);
printf("Socket closed ! n");     
<标题>服务器代码
//... socket initialization, bind and other code
struct_size = sizeof(con_addr);
if( (clientfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size)) < 0 ){
    perror("Could not accept connection. Error: ");
    return 1;
}
// Read message
bytes_read = read(clientfd, client_message, 100);
client_message[bytes_read] = '';
printf("Message received: %s n", client_message);      
// Send message back
n = write(clientfd, client_message , strlen(client_message));    

我得到这样的东西:

Server response: �V��i�8�y�
Server response: ��ƿi�8�{� 

你对TCP套接字的工作方式感到困惑:

  • 服务器通常调用socket(2), bind(2), listen(2), accept(2)来设置其侦听套接字。
  • 客户端先调用socket(2),再调用connect(2)连接服务器。
  • 一旦服务器成功地从accept(2)返回,你有一个双向字节管道在客户端和服务器之间。

当前您似乎正在尝试连接/接受双方。

其他笔记:

  • 总是检查系统调用的返回值- -1是错误的指示,然后检查errno(3)的实际问题(strerror(3)在这里很有用)。
  • 不假设数据是ASCII,所以不使用strlen(3)对套接字输入,使用read(2)的返回值。