2017-04-20 68 views
1

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}); 
    } 
     } 
    }); 
} 
}); 

當用戶試圖加入別人的房間,功能停止在該通知的用戶已經在一個房間裏的「更新」。這是爲什麼?

+0

指南的鏈接在哪裏?我看到的只是? – DiderDrogba344

+0

對不起。這還是一大早在這裏:-)我已經添加它 – JonasSH

+0

它停在用戶已經在一個房間的原因是因爲人[client.id] .inroom不爲空。嘗試添加console.log(people [client.id] [「room」]);在console.log後面(「用戶已經在房間裏了」);並在這裏發佈它打印的內容。 – DiderDrogba344

回答

1

問題是!==。

變化

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

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

未定義!== NULL是給你真實的,但你基本上要未定義的行動,如果它是等同於零。 !==實際上將它們視爲單獨的,而!=會將它們視爲等同的,這就是你想要的。

+0

它完美的工作!謝謝@ DiderDrogba344。我不認爲修復會如此簡單:-) – JonasSH

+0

np!很高興我能幫忙! :) – DiderDrogba344