4

In my game application I would like to have general class for handling socket connection and authorization and several classes for event handling, in such a way:

//loading game/lobby/other socket routers
...

var socketRouter = function(server) {
    var io = Io(server);

    io.use(socketioJwt.authorize({
        secret: config.secretKey,
        handshake: true
    }));

    io.on("connection", function(socket) {
        lobbySocketRouter(socket);
        gameSocketRouter(socket);
        //other routers
        ...

        socket.on("disconnect", function() {
            console.log("DISCONNECTED", socket.id);
        });
    });
};

It's not a problem to generate unique event names for different routers to not interfere with each other. The problem is in disconnect event - I want every router having possibility to perform right action on it. Is it correct to add own handler to disconnect event in every router like this so each of them would trigger:

        //lobbySocketRouter
        socket.on("disconnect", function() {
            //handling lobbySocketRouter special actions
        });
...
        //gameSocketRouter
        socket.on("disconnect", function() {
           //handling gameSocketRouter special actions
        });

?

Arsenii Fomin
  • 3,120
  • 3
  • 22
  • 42
  • you may use rooms and its `join` and `leave` events, it is more flexible than following `disconnect` event for every different events. – İlker Korkut Jun 13 '16 at 13:46

1 Answers1

2
I want every router having possibility to perform right action on it. Is it correct to add own handler to disconnect event in every router like this so each of them would trigger:

"route" I guess you're talking about the Namespaces, you can handle multiples "routers", and then treat each disconnection event depending on the Namespace.

I've wrote in my previous answer a template application to get multiple namespaces inside an Array:

   socket.on('disconnect', disconnectCallback(socket,ns));                        

   function disconnectCallback(socket,ns) {
    return function(msg) {//we return a callback function
      if(ns==="blabla") {
         console.log("Disconnected from blabla");
         socket.broadcast.send("It works! on blabla");
        }
        .
        . 
        .
     }  
   };

You can then create multiple disconnection behaviors based on the Namespace, hope it helps.

Please let me know if you need something else :-)

Community
  • 1
  • 1
Marwen Trabelsi
  • 4,167
  • 8
  • 39
  • 80