Socket.io on socket disconnect

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

问题:

I have this scenario with socket.io:

A socket connects and joins a room and he is the master. Other sockets join his room. When master disconnects I want to kick all other sockets from this room.

I thought of this:

socket.on('disconnect', function(data){     // if socket's id == room  he is the master and kick other sockets from this      // room and join them to a room of their own identified by their ids.        }); 

I want to do this without too much logic and for loops to stall the application. Is it possible to something like io.sockets.leave(socket.room)?

回答1:

alessioalex's answer returns an error because it tries to call "leave" on an array of sockets. This is a working solution:

io.sockets.clients(socket.room).forEach(function(listener) {     listener.leave(socket.room); }); 


回答2:

I am not 100% sure, but after reading Socket.IO's documentation on github I think this should work:

io.sockets.in(socket.room).leave(socket.room); 


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