Socket.io - 在 node.js 的单独文件中监听事件

新手上路,请多包涵

比如我的想法是:

文件1.js

 io.sockets.on('connection', function (socket) {
    socket.on('file1Event', function () {
        //logic
    });
});

文件2.js

 io.sockets.on('connection', function (socket) {
    socket.on('file2Event', function () {
        //logic
    });
});

此代码用于节点服务器,此代码会有问题吗?

原文由 Santos 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 339
2 个回答

不,只需使用相同的“io”对象。

文件1.js

 exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file1Event', function () {
      console.log('file1Event triggered');
    });
  });
}

文件2.js

 exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file2Event', function () {
      console.log('file2Event triggered');
    });
  });
}

应用程序.js

 var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , file1 = require('./File1')(io)
  , file2 = require('./File2')(io)

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

索引.html

 <script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.emit('file1Event');  // 'file1Event triggered' will be shown
  socket.emit('file2Event');  // 'file2Event triggered' will be shown
</script>

原文由 eDwaRd 发布,翻译遵循 CC BY-SA 3.0 许可协议

注意不要为每个文件生成新的连接事件。您应该使用相同的 on(‘connection’) 事件,否则在导入 10 个文件后,您将从节点收到此错误: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit

更好的方法是在主文件中这样做:

 io.on('connection', function (socket) {

  require('pathToSocketRoutesFile1')(socket);
  require('pathToSocketRoutesFile2')(socket);

  require('pathToSocketRoutesFileN')(socket);

  return io;

};

在每个单独的文件中:

 module.exports = function(socket) {

  socket.on('eventName1', function() {
    //...
  });

  socket.on('eventName2', function() {
    //...
  });

};

原文由 kaligrafy 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题