我需要使用可以接受 websocket和标准 http 连接的简单异步websocket 服务器来实现。boost beast
我试过这样的事情:
...
// ws is a boost::beast::websocket::stream<boost::asio::ip::tcp::socket>
ws.async_accept_ex(
[](boost::beast::websocket::response_type& res)
{
res.set(boost::beast::http::field::server, "MyServer");
},
[self](boost::beast::error_code e)
{
if (e) self->ReadHttp();
else self->ReadWs();
}
);
...
void ReadHttp()
{
auto self(shared_from_this());
ws.next_layer().async_read_some(
boost::asio::buffer(data, max_length),
[self](boost::system::error_code ec, std::size_t length)
{
if (!self->ws.next_layer().is_open() || ec==boost::asio::error::eof || ec == boost::asio::error::connection_reset)
// handle disconnection
else if (ec)
// handle error
else
{
std::string s(self->data, length);
cout << "HTTP rx: " << s << endl;
self->ReadHttp();
}
}
);
}
void ReadWs()
{
auto self(shared_from_this());
ws.async_read(
rxData,
[self](boost::beast::error_code ec, std::size_t /*length*/)
{
if(ec == boost::beast::websocket::error::closed)
// handle disconnection
else if ( ec )
// handle error
else
{
std::string s((std::istreambuf_iterator<char>(&self->rxData)), std::istreambuf_iterator<char>());
cout << "WS rx: " << s << endl;
self->rxData.consume(self->rxData.size());
self->Read();
}
}
);
}
但是当 HTTP 客户端连接时,服务器会错过发送的第一条消息。显然,这不是正确的方法:-)
谁能帮我这个?谢谢