Home  >  Q&A  >  body text

One websocket for multiple clients: maximize efficiency and connectivity

I have never used websockets, webworkers and everything related to it before. Obviously, I'm lost and I don't know how to do this correctly.

I've learned how to make a websocket and have it work successfully in the server port. Also, load a web worker (but this doesn't refresh the site directly).

When the user connects, everything works fine. The 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 for the next user connecting via websocket, no longer for other users.

I share a diagram just to make it easier for everyone to understand what I want to do.

One more thing is. What language do I have to use for both the server and the user to get this information? Python, NodeJs, Php (these are the only ones I know how to use).

P粉590929392P粉590929392289 days ago1156

reply all(1)I'll reply

  • P粉476475551

    P粉4764755512023-11-24 11:30:39

    solved!

    Just generate a number assigned to each client (which can be different devices from each other) and then send the random number generated by the server to each connection!

    Before "Connection" you should 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);
    
        ...

    reply
    0
  • Cancelreply