Socket.io emit on Express Route
Attach the io
instance to your app.
app.io = io;
Then you can access it via the request.
router.get('/test', function(req, res) {
req.app.io.emit('tx', {key:"value"});
});
I should note that the more "correct" way to attach data to express is using app.set('io', io)
and app.get('io')
to retrieve it, just in case express started using the io
property for something.
If you are expecting to emit data to a single client you would need keep some kind of session mapping to link a standalone http request to a socket. A session ID might not be a one to one mapping though as you can have many sockets open for one session. You are better off handling a request/response pattern directly with socket.io callbacks.
You can attach the instance to req object also:
app.use(function(req,res,next){
req.io = io;
next();
})
And to emit to a single client
req.io.to(<socketId of cient>).emit(data);