I need to be able to access req from my socket.io event listeners. So I did this:
Server
var express = require('express'),
app = express(),
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
client = require('socket.io').listen(8080).sockets;
app.get('/', function (req, res) {
client.on('connection', function (socket) {
console.log("Connection")
});
res.render('chat');
});
app.listen(config.server.port, function() {
console.log("Listening on port " + config.server.port);
});
Client:
try {
var socket = io.connect('http://127.0.0.1:8080');
} catch(e) {
//Set status to warn user
console.log(e);
}
The problem is that if you add socket.io event listeners inside of an express route handler multiple listeners are created on the socket. If you were to create the pug file and test this code you would notice the console logging "connection" once on first refresh twice on second and so on because each time the route is handled another event listener is being added. I could fix it by moving the listener outside of the route handler however I need to be able to access "req". Is there any solution to this that would allow me to access "req" and prevent excess listeners from being added?