如何在node.js的快速路由中使用socket.io [英] How use socket.io in express routes with node.js
问题描述
我在服务器端将Socket.io与Express一起使用,但是我不能在app.js中使用它,我需要如何在Express路由中使用SocKet.io.
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});
});
});
...
这个工作还可以,但是我还有其他路线可以在其中配置我的方法,POST,GET ... EX
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();
我如何在routesActividad.js和其他类似路由中使用套接字,以便在此路由上使用emit或scoket.
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
...
谢谢
推荐答案
您好,您只需要按参数将IO实例传递给外部模块即可:
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
这篇关于如何在node.js的快速路由中使用socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!