gpt4 book ai didi

javascript - 如何向 Node js中的所有连接的客户端发送广播

转载 作者:行者123 更新时间:2023-11-30 09:32:49 24 4
gpt4 key购买 nike

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

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

是否有任何其他 Node 模块可以实现此目的。 ?

这是使用 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);
});

现在,我的查询是这段代码何时执行,

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

关于javascript - 如何向 Node js中的所有连接的客户端发送广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com