One websocket for multiple clients: maximize efficiency and connectivity
P粉590929392
P粉590929392 2023-11-23 16:52:38
0
1
1104

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粉590929392
P粉590929392

reply all(1)
P粉476475551

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

    ...
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!