Socket.io custom client ID

后端 未结 11 858
栀梦
栀梦 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条回答
  •  一生所求
    2020-12-04 08:39

    This will work with 2.2.0 and above version of Socket.IO

    To set custom Socket Id, generateId function must be overwritten.

    A simple example:

    Server Side

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    io.use((socket, next) => {
      io.engine.generateId = () => {
        // USE ONE OF THESE
        socket.handshake.query.CustomId; // this work for me
        // return socket.handshake.query.CustomId;
      }
      next(null, true);
    });
    
    io.on('connection', function (socket) {
        console.log(socket.id);
    })
    

    Clint Side

    io.connect(URL, { query: "CustomId = CUSTOM ID IS HERE" })
    

    NOTE: *It must be in mind that socket id must be a unique value.

提交回复
热议问题