我正试图让人看到'我的socket.io聊天功能。为此,我需要知道接收器客户端在哪个房间。我怎么能这样做?例如,如果用户向组发送消息我想要检查所有用户当前在该组中的房间,然后说明他们是否在这个房间内。
答案 0 :(得分:0)
The way I do this, is by maintaining a list of connected sockets on the server, add them as they connect (but check for duplicates). You can see what rooms a socket is part of by using socket.rooms
. A user can be part of multiple rooms also, so iirc, socket.rooms is an array or collection of some variety.
Using the below code, you can get a list of users that share a room with the requesting socket.
var connected_sockets = [];
io.on("connection",function(socket){
socket.on("request", function(msg){
var socket = get_user_connection(socket.id);
if(socket == null){
connected_sockets.push(socket); //add if not already
}
var users_in_same_room = [];
for(var x = 0; x < socket.rooms.length; x++){
for(var y = 0 ; y < connected_sockets.length; y++){
if(connected_sockets[y].id == socket.id) continue;
if(is_user_in_room(connected_sockets[y],socket.rooms[x])){
//they share a room
users_in_same_room.push(connected_sockets[y]);
} else {
//they do not share a room
}
}
}
}
});
var get_user_connection = function(socket_id){
for(var x = 0 ; x < connected_sockets; x++){
if(connected_sockets[x].id == socket_id){
return connected_sockets[x];
}
}
return null;
}
var is_user_in_room = function(socket,room_name){
for(var x = 0 ; x < connected_sockets[x].rooms.length; x++){
if(connected_sockets[x].rooms[y] == room_name){
return true;
}
}
return false;
}
Something like the above. I'm sure you could optimize it, but that's the jist of things.