Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io - listen events in separate files in node.js

For example my idea is:

File1.js

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

File2.js

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

This code is for a node server, will I have problems with this code?

like image 401
Santos Avatar asked May 14 '14 11:05

Santos


3 Answers

Nope, just use the same "io" object.

File1.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file1Event', function () {
      console.log('file1Event triggered');
    });
  });
}

File2.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file2Event', function () {
      console.log('file2Event triggered');
    });
  });
}

app.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , file1 = require('./File1')(io)
  , file2 = require('./File2')(io)

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.emit('file1Event');  // 'file1Event triggered' will be shown
  socket.emit('file2Event');  // 'file2Event triggered' will be shown
</script>
like image 178
eDwaRd Avatar answered Nov 17 '22 07:11

eDwaRd


Be careful not to generate a new connection event for each file. You should use the same on('connection') event, otherwise after 10 files imported, you will get this error from node: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit.

The better way is to do like this in your main file:

io.on('connection', function (socket) {

  require('pathToSocketRoutesFile1')(socket);
  require('pathToSocketRoutesFile2')(socket);

  require('pathToSocketRoutesFileN')(socket);

  return io;

};

and in each separate file:

module.exports = function(socket) {

  socket.on('eventName1', function() {
    //...
  });

  socket.on('eventName2', function() {
    //...
  });

};
like image 24
kaligrafy Avatar answered Nov 17 '22 09:11

kaligrafy


Another option is to create a rootSocket which handles the initial connection and then passes the socket to other handlers.

const rootSocket = (io) => {
    io.sockets.on('connection', (socket) => {
        authorization(socket);
        chat(socket);
    });
};
exports.default = rootSocket;
like image 2
fengelhardt Avatar answered Nov 17 '22 07:11

fengelhardt