如何从API路由到达socket.io客户端

时间:2013-10-21 13:05:58

标签: node.js express socket.io

我已连接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
};

1 个答案:

答案 0 :(得分: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 /回调模块的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) {

  });
});