0

我想为我的应用程序创建一个结构,但不知道如何从子路由器调用 socket.io 并将其附加到服务器 express

//app.js

var express = require('express')
 , http = require('http')
 , path = require('path'):
 , i18n = require("i18n");

var app = express();
.
.
app.use(app.router);
require('./routes')(app);
http.createServer(app).listen(app.get('port'), function(){
   console.log("Express port " + app.get('port'));
});

//routes.js

module.exports = function (app) {
 var rou_admin = require('./routers/admin')
 ,   rou_login = require('./routers/login')
 ,   rou_page  = require('./routers/page')
 ,   rou_logou = require('./routers/logout');

function restrict(req, res, next) {
  if (req.session.user){
    next();
  } else {
    res.redirect('/login');
  }
}

//General
app.get('/', rou_page.page); 

//Admin
app.get('/admin', rou_admin.admin);
//xxxx
app.get('/xxxx', rou_admin.xxxx);
//ssss
app.get('/ssss', rou_admin.ssss);
.
.
};

//路由/admin.js

 exports.admin = function(req, res){
  res.render('index',{title: 'Chat Room'})
  var io = require('socket.io').listen(app);

  io.sockets.on('connection', function(socket) {
          ...code...
  }
};

我怎么能这样做,如果你有更好的主意。var io = require('socket.io').listen(app);

4

1 回答 1

1

您已经获得了大部分解决方案。只需进行一些更改:

路由.js

module.exports = function (app) {
var rou_admin = require('./routers/admin')(app),  //pass app to routes/admin.js itself

路线/admin.js

function admin(app)
{

  admin.start= function(req, res){
  res.render('index',{title: 'Chat Room'})
  var io = require('socket.io').listen(app);

          ...code...
  };
}
module.exports = admin;

这里它只是定义了函数,你可以使用 admin.start() 来执行你的代码。

于 2013-02-26T19:02:16.183 回答