c++ - boost websocket 和 io_context 的可重用性以重新建立连接

标签 c++ boost websocket beast-websockets

我在 中使用 boost::beast::websocketboost::asio::io_context 编写了一个小型 websocket 客户端>C++。我有一个具有以下状态的状态机:

enum class State {
    GDR_PROVISING,
    WEBSOCKET_HANDSHAKE,
    REGISTRATION,
    READY,
    CLEANUP,
};

如果代码无法建立连接或建立连接后失败(可能原因:Internet down、Service down、Server 发送关闭帧),则状态机转向CLEANUP 状态并且应该进行清理。

我不确定我是否可以重用相同的 io_contextwebsocket::stream。目前,我的 io_context 仅在这个单线程中使用。我计划使用 websockets 和 io_context 的 pointers 并在 CLEANUP 中删除它们并在 GDR_PROVISING 中再次分配它们。

我可以使用相同的 websocket 和 io_context 实例来重新建立与服务器的连接吗?可能我需要调用一些成员函数,例如 stopreset

我的 READY 现在看起来像这样:

    case State::READY:
    {
        // TODO: Send the Message from the vector
        {
            std::lock_guard<std::mutex> msgGaurd(msgMutex_);
            for (const auto& m: sendMsgQueue_) {
                boost::system::error_code ec;
                pWebStream_->write(boost::asio::buffer(m.toString()), ec);
            }
        }
        // Call io_context run_until to process read messages async because there is no way for non-blocking read in boost for websockets!
        pIoc_->run_until(std::chrono::steady_clock::now() + /* TODO: Add some time_point */);
        break;
    }

    case State::CLEANUP:
    {
        // TODO: Verify if we should delete the stream!
        if (pWebStream_)
            delete pWebStream_;
        if (pIoc_)
            delete pIoc_;
        pWebStream_ = nullptr;
        pIoc_ = nullptr;
        state_ = State::GDR_PROVISING;
        break;
    }

最佳答案

您可以照常重用 io_context。 run 调用不会终止,除非当它尝试执行另一个事件循环迭代时没有更多工作要做。

您还可以使用 get_lowest_layer(*pWebStream_).close() 重用套接字,使用 get_lowest_layer(*pWebStream_).open() 重新打开它,然后调用 async_connect 正常。但是,我认为通过像您一样完全重置对象,您的代码会更清晰。

如果您确实想要重置套接字,我强烈建议您尝试使用 std::optional。它不进行堆分配,您不必担心内存泄漏。

关于c++ - boost websocket 和 io_context 的可重用性以重新建立连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284492/

相关文章:

c++ - 重载 setw( )?

javascript - 通过WebSocket JS发送录制的音频以将Watson语音转换为文本

javascript - 无法使用 JavaScript 关闭 WebSocket

c++ - 在 CMake Env 中包含 libcurl

c++ - 浮点 C++ 编译器选项 |防止 a/b -> a* (1/b)

c++ - C++ 对象构造函数中的 Openmp 使用

c++ - 在内存映射文件中 boost C++ 偏移指针

c++ - 检查类是否有指针数据成员

c++ - OpenTissue boost 绑定(bind)问题

SSL 响应被分成两个回调