【发布时间】:2015-06-04 16:31:45
【问题描述】:
我已经阅读了尽可能多的问题,但我仍然有我的问题......
我有一个非常示例的客户端/服务器套接字:
- 服务器和客户端之间的连接已建立完成
- 从客户端接收消息DONE
- 在服务器端打印消息DONE
- 将消息从服务器发送回客户端问题
- 在客户端打印服务器回复问题
我将消息从客户端发送到服务器没有问题,但是当我发送回消息时,我总是收到奇怪的字符
注意:我在收到的字符串中添加了 '\0' 字符
客户端代码
//... 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] = '\0';
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] = '\0';
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�{�
【问题讨论】:
-
为什么双方都打电话
accept()?要么我(最近没有使用)的套接字代码知识忘记了一些东西,要么这是不对的。我记得只有服务器会调用accept()。此外,listen()不用于“收听回复”。它用于侦听传入的客户端(在调用accept()之前需要)。我认为您在检查电话返回时缺乏错误检查可能会在下层地区困扰您。 -
您的代码在关键函数中没有错误检查。例如,如果
bytes_read是-1,你的代码会做一些疯狂的事情。您不会检查listen、accept、read或write中显示的代码中的错误。你怎么可能希望找出哪里出了问题?