Nodejs:访问快速路由文件中的socket.io实例

时间:2014-09-06 13:23:15

标签: node.js express socket.io

我希望能够从我的快速路由文件向连接到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"
    });
};

1 个答案:

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