Search code examples
c++uwebsockets

How do I periodically send data over a websocket with uWebSockets and C++?


uWS::App::WebSocketBehavior<data> WebSocketBehavior;
    WebSocketBehavior.open = [](uWS::WebSocket<false, true, data> *ws)
    {
       

       
    };

After opening a websocket, I want to perdiodically send a changing value via ws->send(). Is there some way to set a timer with a callback that can do this?

I have managed to implement this by opening another thread in .open and executing it from there, but I want to do it on the same thread as the rest of the program. I have also done it by polling for it from the client side, but I want it to be automatic.


Solution

  • This uses a timer and only one thread:

    #include "App.h"
       
    using namespace std;
    
    struct PerSocketData {};
    
    uWS::WebSocket<false, true, PerSocketData> *gws=nullptr;
        
    int main() {
       auto loop = uWS::Loop::get();
    
       struct us_timer_t *delayTimer = us_create_timer((struct us_loop_t *) loop, 0, 0);
    
       us_timer_set(delayTimer, [](struct us_timer_t *) {
                                   if (gws) {
                                      cout << "calling send" << endl;
                                      gws->send("from server", uWS::OpCode::TEXT);
                                   }
                                }, 1000, 1000);
       
       uWS::App app;
    
       app.ws<PerSocketData>("/*", {
             .idleTimeout = 0,
             .sendPingsAutomatically = false,
             .open = [](auto *ws) {
                        gws = ws;
                     },
             .close = [](auto */*ws*/, int /*code*/, std::string_view /*message*/) {
                         gws = nullptr;
                      }
          }).listen(9001, [](auto *) {
                          });
    
       app.run();
    }