C套接字:回显服务器错误的回复
C sockets: Echo server bad reply
我已经读了很多问题,因为我发现,但我仍然有我的问题....
我有一个非常示例的客户端/服务器套接字:
- 服务器与客户端建立连接完成
- 从客户端接收消息完成
- 在服务器端打印消息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)
的返回值。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- q网络回复 无状态码或错误,但失败
- 错误 = 0x801F0020筛选器回复消息'error_flt_no_waiter_for_reply'微筛选器驱动程序
- C套接字:回显服务器错误的回复