Nodejs include socket.io in router page

2019-05-14 21:06发布

I have an express node app, and I'm trying to keep my code neat by not having all the socket.io stuff in app.js

I don't know the best way to go about this. Here is my initial thought which doesn't feel like the cleanest one

// app.js
var express = require('express')
    , app = express()
    , server = require('http').createServer(app)
    , url = require('url')
    , somePage = require('./routes/somePage.js')
    , path = require('path');

    app.configure(function(){...});

    app.get('/', somePage.index);

and the route

// somePage.js
    exports.index = function (req, res, server) {
        io = require('socket.io').listern(server)
        res.render('index',{title: 'Chat Room'})

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

I feel like I'm close but not quite there

2条回答
Bombasti
2楼-- · 2019-05-14 21:51

I don't know if I'm reading that right but it looks like you are starting a socket server on every request for /, which I'm frankly a little surprised works at all.

This is how I'm separating out the socket.io code from app.js (using express 3.x which is a bit different than 2.x):

// app.js
var express = require('express');
var app = express();

var server_port = config.get('SERVER_PORT');
server = http.createServer(app).listen(server_port, function () {
    var addr = server.address();
    console.log('Express server listening on http://' + addr.address + ':' + addr.port);
});

var sockets = require('./sockets');
sockets.socketServer(app, server);


// sockets.js
var socketio = require('socket.io');
exports.socketServer = function (app, server) {
  var io = socketio.listen(server);

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

Hope that helps!

查看更多
Bombasti
3楼-- · 2019-05-14 22:05

a similar approach is to pass app into index.js file and initiate http and socketio server there.

//app.js
//regular expressjs configuration stuff

require('./routes/index')(app);   //all the app.get should go into index.js

Since app is passed into index.js file, we can do the app.get() routing stuff inside index.js, as well as connecting socketio

//index.js
module.exports = function(app){

var server = require('http').createServer(app)
    ,io = require('socket.io').listen(server);

app.get('/', function(req, res){
 });

server.listen(app.get('port'), function(){
   console.log("Express server listening on port " + app.get('port'));
});


io.sockets.on('connection', function(socket){  
   socket.on('my event', function(data){
   console.log(data);
  });
});

io.set('log level',1);

//io.sockets.emit(...)
查看更多
登录 后发表回答