Reputation: 34667
I'm making a node.js app with sockets.io.
The logic of my app needs to communicate to client through their respective sockets, but the problem with sockets is they're in their own "domain" of code.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
// socket object is only available here
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
See?
I tried to export this socket object out
var Sockets = []
io.sockets.on('connection', function (socket) {
Sockets[socket.handshake.user.id] = socket;
});
Now it's available outside
function myLogic(userid) {
Sockets[userid].emit('free!')
}
But I'm facing weird bugs because it's probably not supposed to be used this way... like new connections make new socket
objects but previous ones still exist somewhere in memory and they still react when their .on('..'
gets fired...
What is the correct way to use socket
s outside of their respective io.sockets.on('connection', function(socket){}
scope?
Upvotes: 1
Views: 1117
Reputation: 19578
Make a setup function for your module and pass it the initialized socket thing. Ie. something like this from main.js:
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var myModule = require('./myModule').setup(io);
Then in your myModule.js save a reference to the io
object:
var localIo;
exports.setup = function(io) {
localIo = io;
};
// Then after in your other code....
function myLocalFunction(myData) {
localIo.sockets.volatile.emit('myevent', {data: myData});
};
Upvotes: 0
Reputation: 1668
Answering your question: if you want to use sockets outside of their respective "io.sockets.on('connection', function(socket){} scope", you have to access them through the io object --> io.sockets.socket(socketId), where socketId is stored somewhere.
Upvotes: 4