DEV
WebSocket 开发
服务端继承 websockets_api,注册工厂;客户端使用 websocket_client。
服务端处理器
必须实现 onopen、onmessage、onclose 以及 run_loop() / async_run_loop()。发送统一走 send()、send_binary()、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 {}
};注册处理器
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);
});
}客户端
客户端 API 为 http::websocket_client:async_connect(url)、async_text_write()、async_text_read(),结果在 recv_data.content。循环回调使用 co_spawn(strand_, ...) 与 add_client_task_loop()。