如何在节点 js 中向所有连接的客户端发送广播 [英] How to send broadcast to all connected client in node js

查看:43
本文介绍了如何在节点 js 中向所有连接的客户端发送广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 MEAN 堆栈的应用程序的新手.它是一个基于物联网的应用程序,使用 nodejs 作为后端.

I'm a newbie working with an application with MEAN stack. It is an IoT based application and using nodejs as a backend.

我有一个场景,我必须向每个连接的客户端发送广播,这些客户端只能打开 Socket 并可以等待任何传入的数据.除非像一个网络浏览器,他们不能执行任何事件,直到现在我已经通过了 Socket.IOExpress.IO 但找不到任何可以有助于实现我想要的发送原始数据以打开套接字连接'

I have a scenario in which I have to send a broadcast to each connected clients which can only open the Socket and can wait for any incoming data. unless like a web-browser they can not perform any event and till now I have already gone through the Socket.IO and Express.IO but couldn't find anything which can be helpful to achieve what I want send raw data to open socket connections'

是否有其他 Node 模块可以实现这一点.?

Is there any other Node module to achieve this. ?

这里是使用WebSocketServer的代码,

Here is the 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, my query is when this code will be 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);
    });
};

这篇关于如何在节点 js 中向所有连接的客户端发送广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆