[英]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: 我有一个非常示例的客户端/服务器套接字:
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'字符
//... 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));
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套接字的工作方式感到困惑:
socket(2)
, bind(2)
, listen(2)
, accept(2)
to setup its listening socket. socket(2)
, bind(2)
, listen(2)
, accept(2)
来设置其监听套接字。 socket(2)
and then connect(2)
to connect to a server. socket(2)
,然后connect(2)
连接到服务器。 accept(2)
you have a bi-directional byte pipe between client and the server. accept(2)
返回,您将在客户端和服务器之间建立一个双向字节管道 。 It looks like currently you are attempting to connect/accept on both sides. 看起来您当前正在尝试在两侧进行连接/接受。
Other notes: 其他说明:
-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)
在此很有用)。 strlen(3)
on socket input, use return value of read(2)
. strlen(3)
,而应使用read(2)
返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.