0

我连接了 x 个客户端。

如果我的 API 发生了某些事情,这意味着如果我从 3 个部分收到数据,我如何将其推送给特定的客户端?

var socketio = require('socket.io');
exports.socketServer = function (app, server) {
  var clients = [];
  var io = socketio.listen(server);
  io.sockets.on('connection', function (socket) {

  });
});

示例 API/回调(这是在另一个文件中)

exports.callback = function(req, res){
    //how do reach my socket.io and my clients from here
};
4

1 回答 1

0

你可以传递io。这是一种方法,在 API/回调文件中

var io;

var initializeSocket = function (socket) {
    io = socket;
}

var callback = function (req, res) {
    // your code here and which will have a reference to io object
}

module.exports = {callback: callback, initializeSocket: initializeSocket};

在此之前,您必须从此处使用 io 对象调用该 Api/callback 模块的 initializeSocket 方法,

var socketio = require('socket.io');
var Api = require(./location_to_your_Api_callback_file);

exports.socketServer = function (app, server) {
  var clients = [];
  var io = socketio.listen(server);
  Api.initilizeSocket(io);
  io.sockets.on('connection', function (socket) {

  });
});
于 2013-10-21T19:30:17.833 回答