[英]Adapting my chat app to work with rooms in socket io
So I have this simple chat application, and I'm looking to adapt it so the users can use the 4 different rooms I created.所以我有这个简单的聊天应用程序,我正在寻找调整它,以便用户可以使用我创建的 4 个不同的房间。 I'll try to explain how it works first, and I need to be guided, what would be the steps I need to take in order to make it work?(considering I'm a beginner) I've tried a lot of things but it always came out really buggy.
我将首先尝试解释它是如何工作的,并且我需要得到指导,我需要采取哪些步骤才能使其工作?(考虑到我是初学者)我已经尝试了很多东西但它总是出来真的有问题。
Client side:客户端:
//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();
}
}
Server side:服务器端:
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}`);
});
});
});
This is the stage I am at right now, and It is definetely not working as it should.这是我现在所处的阶段,它绝对不能正常工作。 I already read a lot of articles about socket.io and rooms, but since english is not my first language I find it hard to understand where the problem is in my code.
我已经阅读了很多关于 socket.io 和房间的文章,但由于英语不是我的第一语言,我发现我很难理解代码中的问题所在。
I think your Server side "message" call might be too nested.我认为您的服务器端“消息”调用可能过于嵌套。 I would do something like this (keeping in mind that sockets maintains a collection of rooms):
我会做这样的事情(请记住 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.