也接受 http 连接的 boost-beast websocket 服务器

boost-beast websocket server that also accept http connections

我需要使用 boost beast 实现一个简单的 异步 websocket 服务器,它可以接受 websocket 标准 http 连接。

我试过这样的事情:

...

// 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 客户端连接时,服务器错过了发送的第一条消息。 显然,这不是正确的方法:-)

谁能帮我解决这个问题? 谢谢

advanced-serveradvanced-server-flex 示例演示了如何构建一个服务器来处理正常的 HTTP 请求,并且还处理 WebSocket 升级请求:

https://github.com/boostorg/beast/tree/e23ecc8ac903b303b9d1a9824b97c092cb3c09bd/example/advanced/server

https://github.com/boostorg/beast/tree/e23ecc8ac903b303b9d1a9824b97c092cb3c09bd/example/advanced/server-flex