首页 > 解决方案 > websocketspp/websockets++ 想要存储作为参数传递的处理程序

问题描述

我需要有关 websocketspp / websockets++ 的帮助(https://github.com/zaphoyd/websocketpp)。

如果这是一个整体更好的选择,我对其他更简单的库(也包括 C)持开放态度:)

我的总体目标是拥有一个 websockets 网页来替代 DikuMUD 的 telnet 客户端。

我一直在使用运行良好的“echo_server”示例。

我正在尝试从一个回调中保存连接处理程序“hdl”,然后稍后重新使用它以将另一条消息发送回客户端。在我看来,hdl 是一个类,每次调用 on_message 时都会在堆栈上创建/销毁。

我想以某种方式存储 hdl,例如在 std::map 中,以便我可以查找它并使用查找的 hdl 稍后将另一条消息发送到同一客户端。

这是示例。抱歉,我已经习惯了 C 和轻量级 C++ :)

std::map<void *, void *> g_cMapHandler;

// Define a callback to handle incoming messages
void on_message(server* s, websocketpp::connection_hdl hdl, message_ptr msg)
{
    void *myExample = 0; // A value I need to be able to retrieve 

    // Using &hdl here doesn't make sense, I presume hdl gets destroyed when on_message ends.
    g_cMapHandler[&hdl] = myExample;

    // But I can't figure out what really represents hdl? Maybe there a fd / file descriptor
    // I can store somehow, and then how do I rebuild a hdl from it?
}

谢谢 :-)

标签: c++websocket

解决方案


connection_hdlistelf 是一个指针,存储connection_hdl。这是一个弱指针。

通常,建议避免void*使用 asio,并使用引用计数智能指针。即使您可以在同步程序中控制对象的生命周期,并在需要时调用free或调用delete,但在异步程序中,流程是变化的,因此每次释放指针的正确位置可能不同。

asio 可以使用boost::weak_ptror std::weak_ptrboost一个有operator <,所以可以直接在地图中使用。For std, there'sstd::weak_ptr<T>::owner_before用于订购,可以通过std::owner_less

std::map<websocketpp::connection_hdl, void *, std::owner_less<websocketpp::connection_hdl>> g_cMapHandler;

推荐阅读