1

我需要使用可以接受 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 客户端连接时,服务器会错过发送的第一条消息。显然,这不是正确的方法:-)

谁能帮我这个?谢谢

4

1 回答 1

1

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

于 2018-07-25T14:00:11.577 回答