NodeJS& Socket.io:控制器中的套接字

时间:2014-06-25 13:09:34

标签: node.js socket.io

我有这段代码:

app.js:

'use strict'
var express = require('express')
  , http = require('http')
  , path = require('path')
  , app = express()
  , fs = require('fs')
  , engine = require('ejs-locals')
  , io = require('socket.io').listen(3872, {log:true})
  , connections = 0;
app.set('port', 80);
app.set('views', __dirname + '/views');
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

fs.readdirSync('./controllers').forEach(function (controller) {
  if(controller.substr(-3) == '.js') {
    var route = require('./controllers/' + controller);
    route.controller(app);
  }
});

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Server runs at port: ' + app.get('port'));
});

io.sockets.on('connection', function (socket) {
  connections++;
  console.log('New connection['+ connections +'] from ' + socket.handshake.address.address);
  socket.emit('pingPong');

  socket.on('disconnect', function() {
    connections--;
    console.log('Lost connection['+ connections +'] from ' + socket.handshake.address.address);
  });
});

/controllers/index.js

var Model = require('../models/index');

module.exports.controller = function(app) {
  app.get('/index', function(req, res) {
    res.redirect('/');
  });

  app.get('/', function(req, res) {
    res.render('index', { _: Model });
  });
}

socket.emit('hoi', {
    message: 'hi'
});

是的,我收到错误' socket未定义'我实际上是在期待,但我不知道如何在控制器中访问socket var。有人知道如何在控制器中发送套接字(带socket.io)吗?

1 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点,最容易想到的是将io实例传递给控制器​​。

fs.readdirSync('./controllers').forEach(function (controller) {
  if(controller.substr(-3) == '.js') {
    var route = require('./controllers/' + controller);
    route.controller(app, io); //Pass it here
  }
});

然后,您可以在导出功能中使用它。

var Model = require('../models/index');

module.exports.controller = function(app, io) {
  app.get('/index', function(req, res) {
    res.redirect('/');
  });

  app.get('/', function(req, res) {
    res.render('index', { _: Model });
  });

  io.on('connection', function(socket) {
    socket.emit('hoi', {
      message: 'hi'
    });
  });
}