Aarosil's answer was great, but I ran into the same problem as Victor with managing client connections using this approach. For each reboot on the client, you will receive on the server the same number of repeated messages (2 repeated = 2 duplicates, 3 = 3 duplicates, etc.).
Turning around aarosil's answer, I used this approach to use the socket object in the routes file and manage messages / manage duplicate messages:
Server internal 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'); }) }); }
source share