我已经阅读了很多问题,但我发现了问题......
我有一个非常样本的客户端/服务器套接字:
我将消息从客户端发送到服务器没有问题,但是当我发回消息时,我总是得到奇怪的字符
注意:我正在添加' \ 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�{�
答案 0 :(得分:4)