socketron

routes for sockets

Socketron

Socketron is an event-driven state machine for routing sockets.

I found when working with socket.io, that:

io.sockets.on('connection', function (socket) {
  var someState = { ... };
  socket.on('this', function (...) { ... });
  socket.on('that', function (...) { ... });
  socket.on('the other thing', function (...) { ... });
  // ... 
});

Didn't scale very well. Organization became difficult, and much spaghetti code ensued.

Install with npm:

npm install socketron

Give it a socket.io instance and you're good to go!

var io = require('socket.io').listen(80);
var socketron = require('socketron');
 
var router = socketron.init(io);
router
  .state({
    name: 'lobby',
    default: true, // this is where newly connected sockets go 
    on: {
      'start:game'function (messagestatesocket) {
        state.moveAllTo(state.parent().getSubstate('game'));
      }
    }
  })
  .state('game', {
    '$add'function (statesocket) {
      state.players[socket.id] = { x: 0, y: 0};
    },
    'move:player'function (messagestatesocket) {
      state.players[socket.id].x = message.x;
      state.players[socket.id].y = message.y;
      state.broadcast('update:player', state.players[socket.id]);
    }
  });
 

MIT