c++ - 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?
}
谢谢 :-)
解决方案
connection_hdl
istelf 是一个指针,存储connection_hdl
。这是一个弱指针。
通常,建议避免void*
使用 asio,并使用引用计数智能指针。即使您可以在同步程序中控制对象的生命周期,并在需要时调用free
或调用delete
,但在异步程序中,流程是变化的,因此每次释放指针的正确位置可能不同。
asio 可以使用boost::weak_ptr
or std::weak_ptr
。boost
一个有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;
推荐阅读
- redirect - 我如何在 wix ridirect 代码中添加几秒钟的缓冲区
- node.js - 无法将数据更新到 MongoDB
- r - 如何从日期中删除日期并仅从 r markdown 中的大型数据集中的列中保留月份和年份?
- cmake - 在 Colcon 构建期间出现“无法复制文件”错误
- r - R中二进制值的随机化测试
- javascript - jQuery获取来自AJAX的while循环数据中的属性值
- javascript - nuxt.js 中反应性的奇怪问题
- swift - 使用集群缩小时,mkmapView 变得非常慢
- python-3.x - 如何在演示文稿中共享交互式 pyplot 图表 [已解决]
- ios - 为什么从搜索栏退出键盘后会留下 UIToolbar?