Socket.io custom client ID

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

    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);
        });
    `
    

提交回复
热议问题