SocketIO: disconnect client by socket id?

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I have a Node server with SocketIO and several connections. How is it possible to disconnect an existing socket based on its ID? There are rooms, an admin in each room and other connections. My goal is to enable the admin socket to make any other socket disconnect based on its ID.

A workaround would be to send a message to the client-to-be-kicked to ping the server back: io.to(socketId).emit('commit-suicide!');, then it sends back an "I-am-so-suicid" message and the server calls socket.disconnect(). Now this is clearly not the optimal solution...

回答1:

On server side you can access io.sockets.connected which holds all connected sockets:

io.sockets.connected[socketId].disconnect();



回答2:

You can hash it in a JSON object

See Socket#id:String

var json = {}; ... //create your serversocket, accept a connection json[Socket.id] = Socket



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!