套接字在Express服务器的单独文件中运行

时间:2014-01-10 13:44:59

标签: javascript express socket.io

我只想在一个单独的文件中实现我的套接字函数(即不在快速服务器实现中),如(/routes/sockets.js)。我怎么能这样做?

我的快递服务器:

var express = require('express')
  , routes = require('./routes')
  , socket = require('./routes/socket.js')
  , http = require('http')
  , path = require('path');
  ,app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
}); 

套接字侦听器(当前与上述服务器实现位于同一文件中)

  sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) { //event on client
        console.log('my other event data ' + data);
      });
    });

1 个答案:

答案 0 :(得分:0)

好的,我自己想通了。您可以使用

调用所需的来源
io.sockets.on('connection', require('./routes/socket'));