Can I separate socket.io event listeners into different modules?

前端 未结 3 1022
孤城傲影
孤城傲影 2020-12-28 11:12

I\'m handling over 15 different socket events, I\'d like to manage certain socket.io events within the modules that are related to those events.

For example, I\'d li

相关标签:
3条回答
  • 2020-12-28 11:15

    Yes you can, using exports and require.

    Check this out.

    0 讨论(0)
  • 2020-12-28 11:17

    I usually split various client related functionality (I usually call them handlers) into individual modules, and then require and use them in whatever file creates the socket.io connection.

    Here is an example module, that exports a function which expects to be passed a socket.io client:

    /* register-handler.js */
    module.exports = function (client) {
      // registration related behaviour goes here...
      client.on('register', function (data) {
        // do stuff
      });
    };
    

    Which is consumed by a file that creates a new socket, listens for connections, and passes them to the handler, which then listens to events on the client.

    /*  main.js */
    // require your handlers
    var handleRegister = require('./register-handler');
    
    // .. set up socket.io
    
    socket.on('connection', function (client) {
      // register handlers
      handleRegister(client);
    });
    
    0 讨论(0)
  • 2020-12-28 11:22

    Here is one way

    socket.on("connection", function (client) {
    
        console.log("Client connected to socket!");
    
        require('./login')(socket, client);
        require('./register')(socket, client);
    });
    

    login.js

    module.exports = function(socket, client) {
        client.on("login", function (data) {
    
            validate(data){
    
                socket.sockets.emit("login_success", data);
    
            }
    
        });
    };
    
    0 讨论(0)
提交回复
热议问题