这就是我到目前为止所得到的,我正在努力寻找一个解决方案,以便:
- 连接始终保持事件状态,因此我可以处理状态更新
- 我可以使用来自 POST 请求的数据向客户端发送 websocket 消息
WS api here
router.post('/', function (req, res) {
// Need to send ws.send() with post data
})
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('r : %s', message);
});
// ws is only defined under this callback as an object of type ws
});
最佳答案
你可以像这样使用事件:
//Create an event
var event = require('events').EventEmitter();
router.post('/', function (req, res) {
// fire an event
event.emit('homePage')
})
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('r : %s', message);
});
// listen the event
event.on('homePage', function(){
ws.emit('someEvent');
});
});
关于node.js - Express 路由器 + WebSocketServer - 在 POST 上发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228392/