我希望能让我的小型聊天室的用户动态地创建他们自己的房间。目前,我在Flask服务器应用程序中使用了常量:
# Predefined rooms for chat
ROOMS = ["Lounge", "news", "games", "coding", "food", "cars"]
用户加入/离开的路由在flask中:
@socketio.on('join')
def on_join(data):
username = data["username"]
room = data["room"]
join_room(room)
# Notofication about new user joined room
send({"msg": username + " has joined the " + room + " room."}, room=room)
@socketio.on('leave')
def on_leave(data):
leave_room(data['room'])
# Notification about leaving users
send({'msg': data['username'] + " has left the " + data['room']}, room=data['room'])
在 JavaScript 方面,它是这样的:
// Select a room
document.querySelectorAll('.select-room').forEach(p => {
p.onclick = () => {
let newRoom = p.innerHTML
// Check if user already in the room
if (newRoom === room) {
msg = `You are already in ${room} room.`;
printSysMsg(msg);
} else {
leaveRoom(room);
joinRoom(newRoom);
room = newRoom;
}
};
});
// Trigger 'join' event
function joinRoom(room) {
// Join room
socket.emit('join', {'username': username, 'room': room});
// Trigger 'leave' event if user was previously on a room
function leaveRoom(room) {
socket.emit('leave', {'username': username, 'room': room});
我该如何让用户动态地加入他们创建的房间?