Use socket.io inside a express routes file

后端 未结 6 1082
刺人心
刺人心 2020-11-28 05:05

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

6条回答
  •  囚心锁ツ
    2020-11-28 05:41

    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');
    
          })
    
       });
    }
    

提交回复
热议问题