【发布时间】:2017-12-31 06:48:55
【问题描述】:
我是使用 MEAN 堆栈的应用程序的新手。它是一个基于物联网的应用程序,并使用 nodejs 作为后端。
我有一个场景,我必须向每个连接的客户端发送广播,这些客户端只能打开套接字并可以等待任何传入数据。除非像网络浏览器一样,它们无法执行任何事件,直到现在我已经通过 Socket.IO 和 Express.IO 但找不到任何有助于实现我想要的东西 send raw data to open socket connections'
是否有任何其他节点模块来实现这一点。 ?
这是使用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);
}
}
【问题讨论】:
-
可以使用websocket广播方式
标签: javascript node.js sockets websocket