我希望能够从我的快速路由文件向连接到socket.io服务器的客户端发送数据。
我的 app.js 如下所示:
var express = require('express');
var app = express();
//routes
require('./routes/test')(app);
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
module.exports = app;
我的 test.js 文件:
module.exports = function(app){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
});
};
答案 0 :(得分:15)
只需将io对象作为参数注入routes模块:
app.js :
var express = require('express');
var app = express();
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
//routes
require('./routes/test')(app,io);
module.exports = app;
test.js :
module.exports = function(app, io){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
io.to('test').emit('some event');
});
};