what happens within run() but outside of handlers?/where should send() be placed?

279 Views Asked by At

I want to send messages whenever I want. However, I don't know where to put send(). I don't actually know what happens after run() is called but not inside a handler.

My current setup is just to send my message in on_open because that's the only place I could put send to get it to work. However, sending multiple messages this way is proving to be a problem. I can close the connection from on_message, but I am unable to send again via that client, regardless of if I connect or run() again.

The ideal solution would be to not have to close and reopen the connection or the endpoint. Again, I would like to know where I should put send if not in on_open or on_message

c.init_asio();
c.start_perpetual();//I've tried both perpetual and non-perpetual 

//[associate handlers]

c.connect(con); //connecting and running works fine;
c.run();        //on_open, on_message work fine
sleep(15);      //is 15 seconds enough for the asio to clean up everything?
c.connect(con); //any permutation of these two lines
c.run();        //do  nothing after close() has been called
std::string test("test");
con->send(test,websocketpp::frame::opcode::TEXT); //this does nothing

using C++11 and VS2015. Also I'm not able to copy/paste the code, so I may have missed some dumb typos.Not sure what else to say. I don't know where I can put send so that I can send it upon a buttonpress, for example

1

There are 1 best solutions below

0
zaphoyd On

When using WebSocket++ with the Asio based transport, the endpoint::run method is just a convenience wrapper around Asio's io_service.run(). There is extensive documentation for Asio about how this works if you want a lot of detail.

In short, run will block indefinitely while performing an event based network I/O loop and will not return until the connection completes.

Sending messages can be done from within that event loop by responding to the various handlers. As you note you can send messages from the open handler. Another common handler to send messages from is the message handler, which would allow you to reply to any message the remote endpoint sent. If you want to send a message independently of network events (open, message received, etc) you can use an interrupt handler (trigger a new event asap) or the timer handler (trigger a new event after a period of time) or set up a thread to send messages whenever you need.

The bundled telemetry_server example demonstrates the timer approach and the telemetry_client example demonstrates the threaded one.