我是一个使用MEAN堆栈的应用程序的新手。它是基于IoT的应用程序,使用nodejs作为后端。
我有一个场景,我必须向每个连接的客户端发送广播,这些客户端只能打开Socket并可以等待任何传入的数据。除非像网络浏览器一样,否则他们无法执行任何事件,直到现在我已经完成了Socket.IO
和Express.IO
,但找不到任何有助于实现我想要的事情{{1 }}“
是否有其他节点模块可以实现此目的。 ?
以下是使用WebSocketServer的代码,
send raw data to open socket connections
现在,我的查询是执行此代码的时间,
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);
});
答案 0 :(得分:2)
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);
});
};