beast icon indicating copy to clipboard operation
beast copied to clipboard

websocket reconnect

Open ahao1995 opened this issue 11 months ago • 3 comments

I want to do reconnect, if read error, should I call async close and then call async_connect. or there is better ways? I find if the error is connection by peer, call async close not call async_close callback, it is right?

using websocket_stream = std::optional<boost::beast::websocket::stream<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>>;
websocket_stream ws_stream_;
ws_stream_->async_read(buffer_, [this](boost::system::error_code ec,
                                         std::size_t n) {
    if (!ec) {
      (read_cb_)(buf, ec);
    }
    else {
    //should call async close or async connect
      async_close();
    }
  });

ahao1995 avatar Mar 14 '24 02:03 ahao1995

beast::websocket::stream is not reusable; you have to construct a new one and go through the process of connection and handshake again. this is just like when you want to create a new websocket stream.

ashtum avatar Mar 14 '24 05:03 ashtum

beast::websocket::stream is not reusable; you have to construct a new one and go through the process of connection and handshake again. this is just like when you want to create a new websocket stream.

if read error, shold I call async close before? or just construct a new stream to do reconnect?

ahao1995 avatar Mar 15 '24 08:03 ahao1995

If read completes with an error, it indicates there is an issue with the connection, so async_close would also complete with an error. Therefore, there is no need to call async_close; the destructor of websocket::stream will forcefully close the underlying socket.

ashtum avatar Mar 15 '24 08:03 ashtum