How use socket.io in express routes with node.js

ε祈祈猫儿з 提交于 2019-12-25 01:18:35

问题


I'm using Express with Socket.io in the server side but i can't use out of app.js, i need how to use SocKet.io in Express routes.

app.js

...  
let http = require('http').Server(app);
let io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
    socket.on('message', (message) => {
        console.log("Message Received: " + message);
        io.emit('message', {type:'new-message', text: message});    
    });  
});
...

this work ok, but i have other routes where configure my methods, POST, GET ... EX

routesActividad.js

...
function http(){ 

  this.configActividad= function(app){
    // get actividades by id
    app.get('/actividad/:NUM_ID_EMPLEADO', function(req, res) {
    //... code here...//
      .then(function (actividad) {              
        res.json(actividad);
      }).catch(error => res.status(400).send(error));
    })

   app.post('/actividad/', function(req, res){
    // code here //
   })

   app.put('/actividad/', function(req, res){
    // code here //
   })
  }
}

module.exports = new http();

how i can use socket in routesActividad.js and other routes like this, for use emit or scoket.on y this routes

app.js

...
var routesActividad = require('./routes/routesActividad');
    routesActividad.configActividad(app);
// more routes
...

thanks


回答1:


Hello you just need to pass the IO instance by parameter to your external module:

app.js

let http = require('http').Server(app);
let io = require('socket.io')(http);
let actividad = require('routesActividad')(io);

routesActividad.js:

function http(io){ 

   //put the IO stuff wherever you want inside functions or outside



  this.configActividad= function(app){
    // get actividades by id
    app.get('/actividad/:NUM_ID_EMPLEADO', function(req, res) {
    //... code here...//
      .then(function (actividad) {              
        res.json(actividad);
      }).catch(error => res.status(400).send(error));
    })

   app.post('/actividad/', function(req, res){
    // code here //
   })

   app.put('/actividad/', function(req, res){
    // code here //
   })
  }
}

module.exports = http; //Removed new statement 


来源:https://stackoverflow.com/questions/50035299/how-use-socket-io-in-express-routes-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!