Reputation: 182
I'm need help with websocketspp / websockets++ please (https://github.com/zaphoyd/websocketpp).
I'm open to other simpler libraries, also C, if that's an overall better option :)
My overall goal is to have a websockets webpage as a replacement for a telnet client for DikuMUD.
I've been using the "echo_server" example which is running fine.
I'm trying to save the connection handler "hdl" from one callback and then re-use it later to send another message back to the client. Looks to me like hdl is a class that will get created / destroyed on the stack with each function call to e.g. on_message.
I would like to store the hdl somehow, e.g. in a std::map so that I can look it up and use that looked up hdl to send another message later to the same client.
Here's the example. Sorry for the void , I'm used to C and lightweight 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?
}
Thank you :-)
Upvotes: 0
Views: 900
Reputation: 13679
connection_hdl
is istelf a pointer, store connection_hdl
. It is a weak pointer.
Generally, suggest avoiding void*
with asio, and using reference-counted smart pointers. Even though you can control lifetime of object in a synchronous program, and call free
or delete
when needed, in asynchronous program the flow is varying, so the right place to free pointer could be different place each time.
asio may use boost::weak_ptr
or std::weak_ptr
. boost
one has operator <
, so can be directly used in a map. For std
, there's std::weak_ptr<T>::owner_before
to be used for ordering, can be used via std::owner_less
std::map<websocketpp::connection_hdl, void *, std::owner_less<websocketpp::connection_hdl>> g_cMapHandler;
Upvotes: 1