node.js从控制器调用ws.send

时间:2017-10-27 11:29:35

标签: javascript node.js express websocket

我想发送一个websocket,使用来自不同控制器的express-ws,而不是路由,我在server.js中有以下代码:

var SocketController = require('./routes/ws.routes');
var app  = express();
var server  = require('http').createServer(app);
var expressWs = require('express-ws')(app);

app.ws('/', SocketController.socketFunction);

SocketController看起来像这样:

exports.socketFunction = function (ws, req) {
    ws.on('message', function(msg) {
        console.log(msg);
        ws.send("hello");
    });
}

是否可以调用

  

ws.send()

来自另一个控制器的

事件?我如何得到" ws"对象

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须将套接字存储在内存中。要从不同模块访问存储的套接字,可以将这些套接字的引用存储在单独的模块中。

例如,您可以创建一个存储所有活动套接字的模块socketCollection。

socketCollection.js:

exports.socketCollection = [];

您可以在定义Web套接字服务器的位置导入此模块:

var socketCollection = require('./socketCollection');
var SocketController = require('./routes/ws.routes');
var app  = express();
var server  = require('http').createServer(app);
var expressWs = require('express-ws')(app);

expressWs.getWss().on('connection', function(ws) {
  socketCollection.push({
    id: 'someRandomSocketId',
    socket: ws,
  });
});

app.ws('/', SocketController.socketFunction);

现在,每当新客户端连接到服务器时,它的引用都将保存到' socketCollection' 您可以通过导入此数组

从任何模块访问这些客户端
var socketCollection = require('./socketCollection');
var ws = findSocket('someRandomSocketId', socketCollection);

var findSocket = function(id, socketCollection) {
   var result  = socketCollection.filter(function(x){return x.id == id;} );
   return result ? result[0].socket : null;
};