how can you tell which socket connection clicked a button using socket.io?

后端 未结 2 479
无人及你
无人及你 2021-01-24 00:11

if you have a a button on the page and you want to make sure the button cannot be clicked again before another socket clicks their button.

if socket a clicked i should d

2条回答
  •  余生分开走
    2021-01-24 01:07

    You can set a UUID for each client (either client side javascript or server side javascript).

    For a server side solution:

    As @slebetman mentioned in the comments, socket.io has a built-in unique identifier for each socket.

    as @slebetman suggested in his answer, to get the socket's unique ID () see his answer for more details):

    // v0.6.x
    var sid = socket.sessionId;    
    
    // v0.7.x
    var sid = socket.id;
    

    For a client side solution:

    If you set the unique ID on the client's side, than you probably need to create your own unique ID.

    I took the following code from 6 revs and Briguy37's answer to a question here on this site:

    function generateUUID(){
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        return uuid;
    };
    

    The randomness should be strong enough for all your clients to have a unique identifier using this ID generator. This should work with the code you wanted to use regarding your question here.

提交回复
热议问题