【问题标题】:Nodejs : access socket.io instance in express routes filesNodejs:在快速路由文件中访问 socket.io 实例
【发布时间】:2014-10-31 06:49:27
【问题描述】:

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

【问题讨论】:

    标签: node.js express socket.io


    【解决方案1】:

    只需将您的 io 对象作为参数注入到路由模块中:

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

    【讨论】:

    • 我从没想过这么简单。所有相关的帖子都在谈论模块导出和其他复杂的东西。好吧,你救了我!谢谢!!
    • 这很好用,只是我需要先检查 io 是否有效 'if (io) { io.to....}'
    猜你喜欢
    • 2013-09-22
    • 2021-03-08
    • 1970-01-01
    • 2018-09-27
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多