Socket.io custom client ID

后端 未结 11 836
栀梦
栀梦 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:34

    or you can override the socket id, like this:

    io.on('connection', function(socket){
    
          socket.id = "YOUR_CUSTOM_ID";
    });
    

    you can see under the array:

    io.sockets.sockets

    0 讨论(0)
  • Do not change the socket IDs to ones of your own choosing, it breaks the Socket.io room system entirely. It will fail silently and you'll have no clue why your clients aren't receiving the messages.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 08:42

    With this 2.2.0 version of Socket.IO, you can achieve this.

    io.use((socket, next) => {
      io.engine.generateId = () => socket.handshake.query.token;
      next(null, true);
    });
    
    0 讨论(0)
  • 2020-12-04 08:45

    I would use an object as a hash lookup - this will save you looping through an array

    var clients = {};
    clients[customId] = clientId;
    
    var lookup = clients[customId];
    
    0 讨论(0)
提交回复
热议问题