Paozhu logoPaozhu Docs
Documentation
DEV

WebSocket guide

Server handlers inherit websockets_api and are registered by a factory; clients use websocket_client.

Server handler

Implement onopen, onmessage, onclose and run_loop() / async_run_loop(). Send through send(), send_binary() and send_close().

websockets/echo_ws.hppcpp
class echo_ws : public http::websockets_api
{
public:
    echo_ws(unsigned int m, unsigned int g) : websockets_api(m, g) { isco = false; }

    void onopen(std::shared_ptr<httppeer> peer) override {}
    void onmessage(std::shared_ptr<httppeer> peer, websocket_frame &msg) override
    {
        send(msg.value);            // use the send ring, not send_writer()
    }
    void onclose(std::shared_ptr<httppeer> peer) override {}
    void run_loop(std::shared_ptr<httppeer> peer) override {}
};

Register the handler

common/websockets_method_reg.hppcpp
// common/websockets_method_reg.hpp
void _initwebsocketmethodregto(WEBSOCKET_REG &methodcallback)
{
    methodcallback.emplace("wstest", [](unsigned int m, unsigned int g)
        -> std::shared_ptr<websockets_api> {
            return std::make_shared<echo_ws>(m, g);
        });
}

Client

The client API is http::websocket_client: async_connect(url), async_text_write(), async_text_read(), with results in recv_data.content. Loop callbacks use co_spawn(strand_, ...) and add_client_task_loop().