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

时间:2018-07-25 06:57:31

标签: c++ boost-beast beast-websockets

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

有人可以帮我吗? 谢谢

1 个答案:

答案 0 :(得分:1)