trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: ws keeping track of connected clients for broadcast #3

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

One solution to keeping track of connected clients:

const connections = {};
const uuid_v4 = require('crypto').randomUUID;
const webserver = new HyperExpress.Server();

function ws_broadcast(data){
    Object.keys(connections).forEach((id) => {
        connections[id].send(data);
    });
}

webserver.ws('/connect', (ws) => {
    // Assign some random identifier to the connection
    ws.id = uuid_v4();

    // Store the connection in our connections object
    connections[ws.id] = ws;

    // Remove the connection from our object once it is closed
    ws.on('close', () => {
        delete connections[ws.id];
     });
});

Reference: https://github.com/kartikk221/hyper-express/discussions/30#discussioncomment-1799623