How to uniquely identify a socket with Node.js

后端 未结 7 1861
时光说笑
时光说笑 2020-12-10 01:25

TLDR; How to identify sockets in event based programming model.

I am just starting up with node.js , in the past i have done most of my coding part in C++ and PHP s

7条回答
  •  爱一瞬间的悲伤
    2020-12-10 02:14

    if you found this question by looking for socket.io unique ids that you can use to differentiate between sockets on the client-side (just like i did), then here is a very simple answer:

    var id = 0; //initial id value
    io.sockets.on('connection', function(socket) {
    
        var my_id = id; //my_id = value for this exact socket connection
        id++; //increment global id for further connnections
    
        socket.broadcast.emit("user_connected", "user with id " + my_id + "connected");
    }
    

    on every new connection the id is incremented on the serverside. this guarantees a unique id.
    I use this method for finding out where a broadcast came from on the clientside and saving data from concurrent sockets.

    for example:

    server-side

    var my_coords = {x : 2, y : -5};
    socket.broadcast.emit("user_position", {id: my_id, coord: my_coords});  
    


    client-side

    user = {};
    socketio.on("user_position", function(data) {
        if(typeof user[data.id] === "undefined")
            user[data.id] = {};
    
        user[data.id]["x"] = data.coord.x;
        user[data.id]["y"] = data.coord.y;
    });
    

提交回复
热议问题