如何判断哪个套接字连接使用socket.io单击了一个按钮? [英] how can you tell which socket connection clicked a button using socket.io?
问题描述
如果您在页面上有一个按钮,并且您想确保在另一个套接字点击其按钮之前无法再次单击该按钮。
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.
如果套接字a单击了我应禁用该按钮,直到另一个套接字发送一条消息,表明他们点击了他们的按钮,然后返回第四个。
if socket a clicked i should disable the button until another socket sends a message that they clicked their button and back and fourth.
$(".buttonTurns").on("click", function(){
socket.emit("turnbutton click")
})
并且当他们连接时他们不输入任何名字
and they dont input any names when they connect
推荐答案
每个socket.io会话都会自动分配一个唯一的字符串作为id。在服务器上,您可以从以下位置获取:
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
如果您的应用程序具有需要的状态要管理,然后一种技术是使用套接字ID作为密钥将它们存储在对象中:
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.
这篇关于如何判断哪个套接字连接使用socket.io单击了一个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!