我在服务器端使用Express和Socket.io,但我不能使用app.js,我需要如何在Express路线中使用SocKet.io。
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
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和其他路由中使用socket,以便使用emit或scoket.on y此路由
app.js
...
var routesActividad = require('./routes/routesActividad');
routesActividad.configActividad(app);
// more routes
...
感谢
答案 0 :(得分:1)
您好,您只需要通过参数将IO实例传递给外部模块:
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