uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance:

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();
    }); 

Suppose we have an implementation of Session like this:

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

Within the Session::process_message function, there is some code that takes a while to complete. How can I hand control back to the event loop to handle other sessions concurrently? In essence, how do I make sure the program is fully asynchronous and can run sessions concurrently?

The library is designed to be asynchronous. Does this mean that the library will manage other connections concurrently, leaving us without any worries?

Answer №1

While in a rest state, uWebSockets will suspend handling other network connections.

Instead of resting, optimize the code for rapid execution by simply acquiring a mutex, queuing tasks, and then releasing the mutex.

Introduce an additional thread (referred to as ProcessingThread) that accesses the same mutex, takes tasks from the queue, releases the mutex, and processes the tasks independently. ProcessingThread can operate at its own pace without affecting the performance of the uWebSockets thread.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for my Vue application failing to load, even though the mounted event is being triggered

Here's an interesting scenario. The code functions correctly in CodePen and even in Stack Overflow's code renderer, but it fails to work on my GitHub Pages site. No errors are triggered, and the console logs for the created and mounted events ex ...

Exploring the Possibilities of Greensock within Meteor Templates

Attempting to add animation to a div within a Meteor template using TweenLite with the gsop package installed. The template html code: <template name="mainInit"> <div id="teaContainer"> <h1>Tea</h1> </div> </template& ...

What is the best way to display JSON data in a readable format?

I received a JSON file with the following structure: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z&q ...

Can anyone provide a method for obtaining a date that is x days earlier through date arithmetic?

Is there a method to obtain the date from 63 days ago with only day, month, and year information needed, excluding hours, minutes, and seconds? I am aware that one can calculate Date object - Date object, but I am curious if it is feasible to derive a dat ...

An error was encountered while linting /app/layout.tsx at line 16: Rule "@typescript-eslint/no-empty-function" was violated due to inability to read properties of undefined (reading 'getTokens')

I am puzzled as to why the function that generates JSX is being checked by the "next lint" script with the rule "@typescript-eslint/no-empty-function". The code snippet at line 16 of the layout.tsx file looks like this: export default function RootLayout( ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

Why is my node.js react app failing to detect the index.html file?

Take a look at the app here: git repository The issue I'm facing is that index.html doesn't seem to be properly linked, resulting in: 1) The website not being responsive for mobile devices 2) Lack of a favicon https://i.sstatic.net/l4hHJ.png ...

Utilizing AngularJS to create an auto complete feature integrated with a SQL Server database

I have a SQL database table with columns as follows: Row1 Row2 Row3 Id Country 1 1a 1b 34 Europe 2 2a 2b 45 US 3 3a 4d 5g Australia I am currently working on implementing an autocomplete feature ...

JavaScript mouse and touch movement events (mousemove, pointermove, touchmove) are not always accurate

I'm currently working on developing a JavaScript whiteboard and have implemented the following code: let lastTimestamp = 0; const fps = 1000/60; document.addEventListener("pointermove", moveMouse, false); function moveMouse (e) { e.preve ...

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Incorporate an additional column into a table using AngularJS

I attempted to insert a new column upon clicking a button, but unfortunately, I was unsuccessful. I have created a JSFiddle demo to illustrate my issue. Any assistance in resolving this problem would be greatly appreciated. Below is my attempt: $scope.a ...

Dynamic JavaScript Animation

Check out this code snippet I currently have. Notice how the text seems to jump when rerun? Give it a try and see for yourself. The big question is: How can this be fixed? $("#aboutUsText").delay(1000).fadeOut(1000) $("#aboutUsText").attr("MyState", "1") ...

Step-by-Step Guide for Attaching Table Legs

I believe that the four legs should be an integral part of the table, rather than just added on like an afterthought. What would be the best way to create new instances of legs and attach them in a way that makes the back legs look slightly smaller than t ...

Error occurs when page rendering is stuck in a recursive loop: Excessive re-renders detected

My webpage contains several form components as listed below. While everything on the front end seems to be working fine, I noticed that the Fetchmovies function is being called repeatedly and an error is thrown in the console: caught Error: Too many re-ren ...

The asynchronous function is not being executed by onSubmit

I am attempting to create a function that will generate a gif when the "get gif" button is pressed. However, I am facing an issue where nothing shows up in the console and the page reloads. 1) The requirement is for the client to enter a value 2) Set th ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

Uncovering targeted information from the current element using $(this) in JavaScript

After running console.log($(this));, I received the following data: https://i.sstatic.net/Wh2p4.png I am looking to combine $(this), access the context, and then move into the attributes. How can I achieve this? ...

Unusual HTML Structure (content misplaced or out of order?)

Recently, I started learning CSS/HTML in school and we just delved into Javascript. Currently, we are working on a website project. However, while trying to integrate the content with the navbar, I encountered a strange issue. When resizing to 620px or le ...