gpt4 book ai didi

javascript - 如何加入socket聊天室

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:05 24 4
gpt4 key购买 nike

this guide的帮助下,我正在尝试建立一个套接字聊天。快完成了,但是用户无法加入其他房间。下面的代码是我的“加入房间功能”:

    client.on("joinRoom", function(id) {  
var room = rooms[id];
if (client.id === room.owner) {
client.emit("update", "You are the owner of this room and you have already been joined.");
} else {
room.people.contains(client.id, function(found) {
if (found) {
client.emit("update", "You have already joined this room.");
} else {
if (people[client.id].inroom !== null) { //make sure that one person joins one room at a time
console.log("User is already in a room");
client.emit("update", "You are already in a room ("+rooms[people[client.id].inroom].name+"), please leave it first to join another room.");
} else {
room.addPerson(client.id);
people[client.id].inroom = id;
client.room = room.name;
client.join(client.room); //add person to the room
user = people[client.id];
socket.sockets.in(client.room).emit("update", user.name + " has connected to " + room.name + " room.");
client.emit("update", "Welcome to " + room.name + ".");
client.emit("sendRoomID", {id: id});
}
}
});
}
});

当用户尝试加入某人的房间时,该功能会在“更新”处停止,通知用户已经在房间中。这是为什么?

最佳答案

问题是!==。

改变

if (people[client.id].inroom !== null) {

if (people[client.id].inroom != null) {

undefined !== null 给你的是 true,但你本质上希望 undefined 表现得好像它等同于 null。 !== 实际上会将它们视为单独的,而 != 会将它们视为等效的,这就是您想要的。

关于javascript - 如何加入socket聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512319/

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