Socket.io custom client ID

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

    why not a simpler solution that does not need to maintain an array of connected clients and does not override internal socket id?

    io.on("connection", (socket) => {
        socket.on('storeClientInfo', (data) => {
            console.log("connected custom id:", data.customId);
            socket.customId = data.customId;
        });
    
        socket.on("disconnect", () => {
            console.log("disconnected custom id:", socket.customId);
        })
    });
    

    Client side

    let customId = "your_custom_device_id";
    socket.on("connect", () => {
        socket.emit('storeClientInfo', { customId: customId });
    });
    

提交回复
热议问题