C++websocket客户端没有接收回调



我们在C#中有一个WebSocket服务器和客户端。服务器被设计为根据客户端读取和处理消息的速度/速度来降低速度。C#客户端一次读取一条消息。

我想用c++编写一个客户端,到目前为止,我查找的所有库都有一个消息处理程序或回调机制,用于接收来自服务器的消息。

这意味着客户端连续接收消息,将其排队,客户端从队列中读取。这不是我们想要的行为。我们要求客户端读取并处理一条消息,处理完成后,读取下一条消息。有什么图书馆可以用来实现这一点吗?

到目前为止,我已经检查了cpprestsdk、websockettpp、libwebsocket

您可以使用Boost.ASIO库。

我制作了一个可以使用Websocket和多个连接的服务器。每个连接都使用异步方式接收数据,这些数据将在接收下一条消息之前处理:

/**
* This method is used to read the incoming message on the WebSocket
* and handled it before reading the other message.
*/
void wscnx::read()
{
if (!is_ssl && !m_ws->is_open())
return;
else if (is_ssl  && !m_wss->is_open())
return;
auto f_read = [self{shared_from_this()}](const boost::system::error_code &ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if (ec == websocket::error::closed)
{
self->close(beast::websocket::close_code::normal, ec);
return;
}
if (ec)
{
self->close(beast::websocket::close_code::abnormal, ec);
return;
}
std::string data = beast::buffers_to_string(self->m_rx_buffer.data());
self->m_rx_buffer.consume(bytes_transferred);
if (!self->m_server.expired())
{
std::string_view vdata(data.c_str());
/*************************************
Here is where the datas are handled
**************************************/
self->m_server.lock()->on_data_rx(self->m_cnx_info.id, vdata, self->cnx_info());
}

/*************************************
Read the next message in the buffer.
**************************************/
self->read(); 
};//lambda
if (!is_ssl)
m_ws->async_read(m_rx_buffer, f_read);
else
m_wss->async_read(m_rx_buffer, f_read);
}

在这个示例中,连接可以是普通的,也可以是安全的,使用SSL,两者都使用lambda函数来接收数据。

我在浏览器上用JS应用程序测试了这项服务,处理每条消息的顺序没有问题。

最新更新