I\'m trying to use Socket.io with Node.js and emit to a socket within the logic of a route.
I have a fairly standard Express 3 setup with a server.js file that sits
aarosil's answer was great, but I ran into the same problem as Victor with managing client connections using this approach. For every reload on the client, you'd get as many duplicate messages on the server (2nd reload = 2 duplicates, 3rd = 3 duplicates, etc).
Expanding on aarosil's answer, I used this approach to use the socket object in my routes file, and manage the connections/control duplicate messages:
Inside Server File
// same as aarosil (LIFESAVER)
const app = require('express')();
const server = app.listen(process.env.PORT || 3000);
const io = require('socket.io')(server);
// next line is the money
app.set('socketio', io);
Inside routes file
exports.foo = (req,res) => {
let socket_id = [];
const io = req.app.get('socketio');
io.on('connection', socket => {
socket_id.push(socket.id);
if (socket_id[0] === socket.id) {
// remove the connection listener for any subsequent
// connections with the same ID
io.removeAllListeners('connection');
}
socket.on('hello message', msg => {
console.log('just got: ', msg);
socket.emit('chat message', 'hi from server');
})
});
}