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: Broadcast using subscribe / publish 'topic' #9

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

Another approach to broadcast to clients. This one have the option of only broadcast to clients subscribing to the channel / topic.

const crypto = require('crypto');
const HyperExpress = require('hyper-express');
const Server = new HyperExpress.Server();

// Create an endpoint for accepting websocket connections
Server.ws('/connect', (ws) => {
    // Attach a unique identifier to each connection
    ws.id = crypto.randomUUID();

    // Subscribe the connection to "OUR_TOPIC_NAME"
    ws.subscribe('OUR_TOPIC_NAME');
    console.log(`Websocket Connection ${ws.id} Is Now Connected & Subscribed To OUR_TOPIC_NAME!`);

    // Bind any handlers here for this connection, we will bind the close handler so we can log closure
    ws.on('close', (code, message) => {
        console.log(`Websocket Connection ${ws.id} Has Disconnected!`);
    });
});

// Now you can publish a message to all connections over the "OUR_TOPIC_NAME" topic like below
Server.publish('OUR_TOPIC_NAME', 'This is a message for OUR_TOPIC_NAME subscribers!');

Source: https://github.com/kartikk221/hyper-express/issues/54#issuecomment-1046051251