如何制作同步聊天程序以同步发送和接收消息

How to make a synchronous chat program to send and receive messages synchronously?

本文关键字:同步 消息 何制作 聊天 程序      更新时间:2023-10-16

目前我正在用 c++ 创建一个客户端服务器控制台应用程序。通过使用winsock2.h库和UDP协议,我们使用sendtorecvfrom将消息作为字符串从客户端发送到服务器,然后将消息发送到不同的客户端,现在如果客户端1向客户端2发送消息,客户端2将不会收到消息,直到他们尝试向客户端1发送消息。我希望使程序像即时通讯程序一样工作,以便当客户端 1 向客户端 2 发送消息时,客户端 2 几乎可以立即收到它,而无需先发送消息。

此外,如果客户端 1 要向客户端 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 套接字接口具有文档中描述的等效映射。