At the moment I have a getter/setter socket module as follows
var socket;
module.exports.getSocket = getSocket;
module.exports.setSocket = setSocket;
function getSocket() {
return socket;
}
function setSocket(sock) {
if (undefined == socket) socket = sock;
}
In app.js I set as follows
var sio = require('./lib/socket');
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
sio.setSocket(socket);
});
In my module I use as follows
sio = require('./lib/socket');
socket.getSocket().broadcast.emit(...);
It seems a bit contrived is there a better way to do this?
Edit: I would like a general solution to the problem of firing off a message which is not initiated by the client socket. For example suppose I retrieve stock prices from an external source and wish to fire an event on price update. Since it is not client initiated, how can I get access to the socket? Or alternatively let's say I wish to fire off a socket message in response to a POST request. Once again I'm not sure how I would access the socket.