[英]Adapting my chat app to work with rooms in socket io
所以我有這個簡單的聊天應用程序,我正在尋找調整它,以便用戶可以使用我創建的 4 個不同的房間。 我將首先嘗試解釋它是如何工作的,並且我需要得到指導,我需要采取哪些步驟才能使其工作?(考慮到我是初學者)我已經嘗試了很多東西但它總是出來真的有問題。
客戶端:
//Get the room name out of the URL and send it to the server
function getRoomName() {
let roomName = window.location.toString();
if(roomName.includes('#') === true){
roomName = roomName.split("#");
roomName.splice(0, 1);
roomName = roomName.toString();
// Join room
socket.emit('joinRoom', roomName);
}
}
//Here I am changing the URL when clicking on a room button (I got one of these for each button)
proiectFinalRoom.addEventListener('click', () =>{
window.location.href='#proiectFinal';
roomNameEdit.innerHTML = "#PROIECT-FINAL";
})
sendBtn.addEventListener('click', () =>{
sendMessage();
})
//Here I am sending the message to the server
function sendMessage(){
if(messageInput.value === ""){
return;
} else {
//Calling the getRoomName function (when sending a message)
getRoomName();
const text = messageInput.value;
socket.emit('message', text);
displayMessage();
}
}
服務器端:
io.on('connection', (socket) => {
socket.on('joinRoom', function(roomName){
//Join room
socket.join(roomName);
//Send messages
socket.on('message', (message) => {
socket.broadcast.to(roomName).emit('message', `${message}`);
});
});
});
這是我現在所處的階段,它絕對不能正常工作。 我已經閱讀了很多關於 socket.io 和房間的文章,但由於英語不是我的第一語言,我發現我很難理解代碼中的問題所在。
我認為您的服務器端“消息”調用可能過於嵌套。 我會做這樣的事情(請記住 sockets 維護一組房間):
io.on('connection', (socket) => {
socket.on('joinRoom', function(roomName){
//Join room
socket.join(roomName);
});
//Send messages
socket.on('message', (message) => {
var room = getRoom(socket);
socket.to(room).emit('message', `${message}`);
});
});
function getRoom(socket) {
var room;
for (let aRoom of socket.rooms) {
if (aRoom !== socket.id) {
room = aRoom;
}
}
return room;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.