Socket.io custom client ID

后端 未结 11 873
栀梦
栀梦 2020-12-04 07:59

I\'m making a chat app with socket.io, and I\'d like to use my custom client id, instead of the default ones (8411473621394412707, 1120516437992682114

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 08:29

    To set custom socket id, generateId function must be overwritten. Both of eio and engine props of Socket.io server object can be used for to manage this operation.

    A simple example:

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    io.engine.generateId = function (req) {
        // generate a new custom id here
        return 1
    }
    
    io.on('connection', function (socket) {
        console.log(socket.id); // writes 1 on the console
    })
    

    It seems to be it has been handled.

    It must be in mind that socket id must be unpredictable and unique value with considering security and the app operations!

    Extra: If socket.id is returned as undefined because of your intense processes on your generateId method, async/await combination can be used to overcome this issue on node.js version 7.6.0 and later.
    handshake method of node_modules/engine.io/lib/server.js file should be changed as following:

    current:

    // engine.io/lib/server.js
    
    Server.prototype.generateId = function (req) {
      return base64id.generateId();
    };
    
    Server.prototype.handshake = function (transportName, req) {
      var id = this.generateId(req);
      ...
    }
    

    new:

    // function assignment
    
    io.engine.generateId = function (req) {
      return new Promise(function (resolve, reject) {
        let id;
        // some intense id generation processes
        // ...
        resolve(id);
      });
    };
    
    
    // engine.io/lib/server.js
    
    Server.prototype.handshake = async function (transportName, req) {
      var id = await this.generateId(req);
      ...
    }
    

    Note: At Engine.io v4.0, generateId method would accept a callback. So it would not needed to change handshake method. Only generateId method replacement is going to be enough. For instance:

    io.engine.generateId = function (req, callback) {
      // some intense id generation processes
      // ...
      callback(id);
    };
    

提交回复
热议问题