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

后端 未结 2 476
无人及你
无人及你 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:12

    Every socket.io session is automatically assigned a unique string as an id. On the server you can get it from:

    socket.id
    

    If you are inside a session (that is, the connection that returns the socket object) you can send messages back to the client by simply doing:

    socket.emit('event name',data);
    

    But if you want to send a message to a different session then you need to do:

    io.sockets.socket(socket_id).emit('event name',data);
    

    If you want to send a message to all connected sessions then just do:

    io.emit('event name', data); // broadcast
    

    If your application have state that needs to be managed, then one technique is to store them in an object using the socket id as the key:

    var buttonState = {}
    
    io.on('connection',function('socket'){
        // default button to off when socket connects:
        bottonState[socket.id] = 'off';
    
        socket.on('on button',function(){
            bottonState[socket.id] = 'on';
        })
    
        socket.on('off button',function(){
            bottonState[socket.id] = 'off';
        })
    })
    

    Now that you can manage the individual state for each individual client on the server you can use that to communicate them to other clients.

提交回复
热议问题