javascriptc++asynchronouslibuvuwebsockets

uWebSockets concurrent sessions


for the sake of simplicity, let's assume I have only one uWebSockets instance running on my server:

struct UserData
{
   uWS::WebSocket<true, uWS::SERVER> *ws;
   bool logged_in = false;
   ID user_id; 
};
uWS::SSLApp()
          .ws<UserData>(
              "/*",
              { 
               .open =
                   [](auto *ws, auto *req) {
                     std::cout << "user with ip: " << ws->getRemoteAddress()
                               << " connected" << std::endl;
                   },
               .message =
                   [](auto *ws, std::string_view message,
                      uWS::OpCode opCode) {
                     auto userData = static_cast<UserData *>(ws->getUserData());
                     // give websocket pointer to a session
                     userData->ws = ws;
                     Session session;
                     session.process_message(userData, message);
                   } 
          .listen(9001,
                  [](auto *token) {
                    if (token)
                      std::cout << "listening on port 9001" << std::endl;
                    else
                      std::cout << "failed to listen on port 9001" << std::endl;                            
                  })
          .run();
    }); 

possible implementation of Session:

class Session {
    process_message(UserData &userData, const std::string_view &message) {  
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

inside the function Session::process_message, I have a code that takes a long time to finish. How do I return control to the event loop in order for it to process some other sessions? In other words, how do I design the program to be fully asynchronous/run session concurrently?

The library is asynchronous. does it mean that the library will handle the other connections concurrently and I have nothing to worry about?


Solution

  • During the sleep, uWebSockets will not process other network connections.

    Change the sleep to fast code that only gets a mutex, adds to a queue, and releases a mutex.

    Make another thread (let's call it ProcessingThread) that gets the same mutex, removes messages from that queue, releases the mutex, and processes the messages. ProcessingThread may take as long as it needs to process messages without slowing down the uWebSockets thread.