javascript - How to send broadcast to all connected client in node js -
i'm newbie working application mean stack. iot based application , using nodejs backend.
i have scenario in have send broadcast each connected clients can open socket , can wait incoming data. unless web-browser can not perform event , till have gone through socket.io , express.io couldn't find can helpful achieve want send raw data open socket connections'
is there other node module achieve this. ?
here code using websocketserver,
const express = require('express'); const http = require('http'); const url = require('url'); const websocket = require('ws'); const app = express(); app.use(function (req, res) { res.send({ msg: "hello" }); }); const server = http.createserver(app); const wss = new websocket.server({ server }); wss.on('connection', function connection(ws) { ws.on('message', function(message) { wss.broadcast(message); } } wss.broadcast = function broadcast(msg) { console.log(msg); wss.clients.foreach(function each(client) { client.send(msg); }); }; server.listen(8080, function listening() { console.log('listening on %d', server.address().port); }); now, query when code executed,
wss.on('connection', function connection(ws) { ws.on('message', function(message) { wss.broadcast(message); } }
var websocketserver = require("ws").server; var wss = new websocketserver({port:8100}); wss.on('connection', function connection(ws) { ws.on('message', function(message) { wss.broadcast(message); } } wss.broadcast = function broadcast(msg) { console.log(msg); wss.clients.foreach(function each(client) { client.send(msg); }); };
The example describes a common real-time communication requirement in a Node.js IoT application: sending a message received from one WebSocket client to all currently connected clients. The ws implementation keeps track of connected clients and uses wss.clients to iterate through them and send the incoming message as a broadcast.
ReplyDeleteThe separation between the WebSocket server, connection handler, and broadcast() function makes the flow easy to follow: a client sends a message, the server receives it, and the same message is forwarded to each connected socket. This is a useful pattern to understand when learning server-side JavaScript through a Nodejs Course.
The example also demonstrates how Express can provide the HTTP application while the WebSocket layer handles persistent connections and real-time events. Combining these two responsibilities is particularly relevant for IoT applications, where a Expressjs Course can help developers understand how the HTTP and real-time communication layers fit together.
ReplyDelete