Socket.io custom client ID

2019-01-13 00:13发布

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). Is there any ways of sending the custom identifier when connecting or just using something to track a custom name for each ID? Thanks!

8条回答
劫难
2楼-- · 2019-01-13 00:41

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];
查看更多
虎瘦雄心在
3楼-- · 2019-01-13 00:48

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.

查看更多
乱世女痞
4楼-- · 2019-01-13 00:48

If you are trying to use a custom id to in order to communicate with a specific client then you can do this

io.on('connection', function(socket){
    socket.id = "someId"
    io.sockets.connected["someId"] = io.sockets.connected[socket.id];

    // them emit to it by id like this
    io.sockets.connected["someId"].emit("some message", "message content")
});
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-13 00:48

Can store customId (example userId) in object format instead of for loop, this will improve performance during connection, disconnect and retrieving socketId for emitting

`

 var userId_SocketId_KeyPair = {};
 var socketId_UserId_KeyPair = {};

_io.on('connection', (socket) => {
    console.log('Client connected');
    //On socket disconnect
    socket.on('disconnect', () => {
        // Removing sockets
        let socketId = socket.id;
        let userId = socketId_UserId_KeyPair[socketId];
        delete socketId_UserId_KeyPair[socketId];
        if (userId != undefined) {
            delete userId_SocketId_KeyPair[userId];
        }
        console.log("onDisconnect deleted socket with userId :" + "\nUserId,socketId :" + userId + "," + socketId);
    });

    //Store client info
    socket.on('storeClientInfo', function (data) {
        let jsonObject = JSON.parse(data);
        let userId = jsonObject.userId;
        let socketId = socket.id;
        userId_SocketId_KeyPair[userId] = socketId;
        socketId_UserId_KeyPair[socketId] = userId;
        console.log("storeClientInfo called with :" + data + "\nUserId,socketId :" + userId + "," + socketId);
    });
`
查看更多
乱世女痞
6楼-- · 2019-01-13 00:52

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);
};
查看更多
可以哭但决不认输i
7楼-- · 2019-01-13 00:55

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

查看更多
登录 后发表回答