简体   繁体   English

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

[英]C sockets: Echo server bad reply

I've read as many questions as I've found, still I have my problem.... 我已经阅读了许多发现的问题,但仍然有我的问题...。

I have a very sample client/server socket: 我有一个非常示例的客户端/服务器套接字:

  • Connection stablished between server and client DONE 服务器与客户端之间的连接已建立完成
  • Receive message from client DONE 接收来自客户端的消息完成
  • Print the message in the server side DONE 在服务器端打印消息完成
  • Send message back from server to client PROBLEMS 从服务器发送信息回客户端问题
  • Print the server reply in the client side PROBLEMS 打印在客户端问题的服务器响应

I send the message from client to server without problems, but when I send back the message I'm allways getting weird characters 我将消息从客户端发送到服务器没有问题,但是当我发回消息时,我总是收到奇怪的字符

Note: I'm adding the '\\0' character to the received string 注意:我在接收到的字符串中添加了'\\ 0'字符

Client code 客户代码

//... 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");     

Server Code 服务器代码

//... 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));    

I'm getting things like this: 我正在得到这样的事情:

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

You are confused on how TCP sockets work: 您对TCP套接字的工作方式感到困惑:

It looks like currently you are attempting to connect/accept on both sides. 看起来您当前正在尝试在两侧进行连接/接受。

Other notes: 其他说明:

  • Always check return values of system calls - -1 is an indication of an error, then inspect errno(3) for the actual problem ( strerror(3) is useful here). 始终检查系统调用的返回值-1表示错误,然后检查errno(3)中的实际问题( strerror(3)在此很有用)。
  • Do not assume the data is ASCII, so not use strlen(3) on socket input, use return value of read(2) . 不要假定数据是ASCII,因此不要在套接字输入上使用strlen(3) ,而应使用read(2)返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM