问题
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:
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 thatio
value to create its ownio.on('connection', socket => { socket.on('someMsg', localHandler)} );
.Export
io
from your main socket.io module and then have every module that wants to listen to an incoming messageimport/require()
the main socket.io module (to get theio
value) and then use thatio
value to create its ownio.on('connection', socket => { socket.on('someMsg', localHandler)} );
.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