gpt4 book ai didi

node.js - 如何拒绝某些用户加入socket.io中的同一房间?

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:14 25 4
gpt4 key购买 nike

现在我正在使用express4和socket.io 0.9构建在线聊天室。问题是我不希望同一用户在浏览器(或其他浏览器)中打开另一个选项卡时加入同一个房间。我可以获取用户 session (要访问这些房间,用户必须登录,当他们登录时,“uid”将设置到 session 中)。

最佳答案

在@Jujuleder的帮助下,我找到了解决我的问题的方法。

服务器:

var socketio = require('socket.io'),
cookieParser = require('cookie-parser')('YOUR-SERECT-KEY'),
session = require('express-session'),
RedisStore = require('connect-redis')(session),
redis = require("redis"),
client = redis.createClient(6379, "127.0.0.1"),
store = new RedisStore;

module.exports.listen = function(app){
var io = socketio.listen(app);
var pubRoom = new PublicRoom(io);
pubRoom.listen();
return io
};

function PublicRoom(io){
this._baseUrl = '/room/public/';
this.publicRoom = io.of(this._baseUrl);
}

PublicRoom.prototype.listen = function(){
this.publicRoom.authorization(function(handshakeData, callback){

function cookieParserWrapper (handshakeData, next) {
cookieParser(handshakeData,{}, next);
}

cookieParserWrapper(handshakeData,function(){});

var sid = handshakeData.signedCookies.sid;
//get the UID from redis
store.get(sid,function(err,data){
if(err){
console.log(err);
}else{
handshakeData.uid = data.uid;//set UID into handshake
callback(null, true);
}
});
});

this.publicRoom.on('connection', function(socket){
socket.on('authReq',function(room,user){
socket.myID = user;
var uid = socket.handshake.uid; // We can get the UID here.
var onlineUsers = self.publicRoom.clients(room);//get users in this room
if(onlineUsers.length === 0){
socket.to(room).emit('authRes',true);// Tell the client you can Join
socket.auth = true;
}else{
for(var i= 0,l=onlineUsers.length;i<l;i++){
if(onlineUsers[i].myID===uid){
socket.auth = false;
socket.to(room).emit('authRes',false);
// Tell the client you can't Join
}else{
socket.auth = true;
socket.to(room).emit('authRes',true);// Tell the client you can Join
}
}
}
});
});
}

客户:

socket.on('connect', function() {
socket.emit('authReq',roomID,userID);
});

关于node.js - 如何拒绝某些用户加入socket.io中的同一房间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23520019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com