如何制作同步聊天程序以同步发送和接收消息
How to make a synchronous chat program to send and receive messages synchronously?
目前我正在用 c++ 创建一个客户端服务器控制台应用程序。通过使用winsock2.h
库和UDP协议,我们使用sendto
和recvfrom
将消息作为字符串从客户端发送到服务器,然后将消息发送到不同的客户端,现在如果客户端1向客户端2发送消息,客户端2将不会收到消息,直到他们尝试向客户端1发送消息。我希望使程序像即时通讯程序一样工作,以便当客户端 1 向客户端 2 发送消息时,客户端 2 几乎可以立即收到它,而无需先发送消息。
,则客户端 1 将无法发送另一条消息,除非客户端 2 回复了第一条消息。
如果您需要更多信息或查看一些代码,请询问。
发送代码:
while( getline( cin, line ) )
{
// send a string to the server.
sendto( hSocket, line.c_str(), line.size(), 0,
reinterpret_cast<sockaddr*>( &serverAddress ),
sizeof( serverAddress ) );
// recieve the response.
int n = recvfrom( hSocket, recvLine, MAXLINE, 0, NULL, NULL );
if( n == -1 )
{
cout << "no reply" << endl;
}
else
{
recvLine[n] = 0;
string const terminateMsg = "server exit";
string msg = recvLine;
if( msg == terminateMsg )
{
cout << "Server terminated" << endl;
break;
}
cout << n << ": " << recvLine << endl;
}
}
现在,如果客户端 1 向客户端 2 发送消息,则客户端 2 不会接收消息,直到他们尝试向客户端 1 发送消息。
你已经这样编码了。
此外,如果客户端 1要向客户端 2 发送消息,则客户端 1 不会能够发送另一条消息,除非客户端 2 已回复第一个。
同样,您已经以这种方式对其进行了编码。您的代码假定每个sendto()
后跟一个recvfrom()
。但是你的问题表明这不是你想要的。我在下面的代码中添加了一些注释
while( getline( cin, line ) )
{
// send a string to the server. <-- will never get here a 2nd time through the loop without recvfrom() returning
sendto( hSocket, line.c_str(), line.size(), 0,
reinterpret_cast<sockaddr*>( &serverAddress ),
sizeof( serverAddress ) );
// recieve the response. <--- will never get here without getline() returning
int n = recvfrom( hSocket, recvLine, MAXLINE, 0, NULL, NULL );
if( n == -1 )
{
cout << "no reply" << endl;
}
else
{
recvLine[n] = 0;
string const terminateMsg = "server exit";
string msg = recvLine;
if( msg == terminateMsg )
{
cout << "Server terminated" << endl;
break;
}
cout << n << ": " << recvLine << endl;
}
}
使用我希望使该程序像即时通讯工具一样工作,所以当客户端 1 向客户端 2 发送消息时,客户端 2 将收到它几乎立即无需先发送消息。
Boost.Asio 和异步套接字,异步chat_client示例使用 TCP 套接字完美地完成了这件事,修改 UDP 的示例是相当简单的。异步 UDP 回显服务器示例也可能很有用。您需要使用 boost::asio::ip::udp::socket::async_recv_from()
和 boost::asio::ip::udp::socket::async_send_to()
。其他 BSD 套接字接口具有文档中描述的等效映射。
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 松弛原子与无同步情况下的记忆连贯性
- 如何通过参数抛出错误消息
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- 在C++中同步线程
- C++入门 5 版:类消息和文件夹
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 与 stdio 同步是否使程序 I/O 非交互式?
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 如何在qt中同步应用程序和显示器的刷新率?
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 如何制作同步聊天程序以同步发送和接收消息