Node Socket.IO socket.on() across multiple files

白昼怎懂夜的黑 提交于 2020-01-06 09:54:30

问题


I'm using Socket.IO in a node app and I wish to catch and respond to socket events in different files, how do I do it?

One solution that I was able to find was to do this in the file that sets up the socket.io:

var events = [];
module.exports.setup = (server) => {
  io = require('socket.io')(server);
  console.log("Socket.io setup complete");
  io.on('connection', (socket) => {
    for(let e of events){
      socket.on(e.event, e.callback);
    }
  });
};

module.exports.on = (event, callback) => {
  events.push({event: event, callback: callback});
};

This works just fine, the only problem is that I can't reach the socket object, thus I don't know which socket emitted the event.

EDIT

Well I guess one other way is to pass the socket in the cb as the first argument, but maybe there is a better way.


回答1:


There are different ways to structure things depending upon how your code is structured and how you might want to reuse or structure your modules. Here are some of the choices:

  1. Pass io to every module's constructor that wants to listen for incoming socket.io events and let every module that wants to listen for a message, use that io value to create its own io.on('connection', socket => { socket.on('someMsg', localHandler)} );.

  2. Export io from your main socket.io module and then have every module that wants to listen to an incoming message import/require() the main socket.io module (to get the io value) and then use that io value to create its own io.on('connection', socket => { socket.on('someMsg', localHandler)} );.

  3. Have your main socket.io module export a function for registering a listener for an incoming socket.io message and then just have one io.on('connection', ...) handler in your main socket.io module that listens for all the events that were requested.



来源:https://stackoverflow.com/questions/48063925/node-socket-io-socket-on-across-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!