Using a single websocket for a multiple clients

Question:

I’ve never used before websockets neither web workers and everything around that. Obviously, I’m lost and I don’t know how to make it properly.

I’ve learned how to make a websocket and leave it working in a server port successfully. As well, load a web worker (but this one can’t refresh the website straight).

When a user is connected, everything is working fine. Websocket is sending messages to the user and the user is refreshing their website.

The problem is when I want to use it with many other users (different tabs or browsers to simulate different users). Only works with next user is connected with websocket, is not working anymore with the other users.

I share a diagram just to make it simple to understand what I want to do.

Another point is. Which language do I have to use to get this, both for the server and for the users? Python, NodeJs, Php (those are the only I know how to use).

enter image description here

Asked By: Carlos Diaz

||

Answers:

SOLVED!

Just I generate a number assigned to each client (can be different device between each other) and I send the random number generated by server to each connection!

Before "connection" you shoul add:

const WS = require('ws');
const WS_PORT = 8081
const express = require('express');
const app = express();
const PORT = 3000;

app.listen(PORT, () => console.log(`Server listening , go to http://localhost:${PORT}`));
app.use(express.static('public'));


const wss = new WS.Server({ port: WS_PORT })

const wsSelected = new Set();
// Creating connection using websocket

const interval = setInterval(() => {
    const randomNumber = Math.floor(Math.random() * 100);
    //Sending same number to each client
    wsSelected.forEach(ws => 
        ws.send(randomNumber)
    )
}, 2000);

After "connection" you should add:

wss.on("connection", ws => {
    console.log("New client!");
    
    //This line you should add
    wsSelected.add(ws);

    ...
Answered By: Carlos Diaz