You are missing 2 things.
1st, you need to send a "join"
event to the server.
<script>
function joinRoom() {
console.log("ask server to join room");
socket.emit("join", { "user": Date.now(), "room": "Notifications" });
}
</script>
<body>
<button onclick="joinRoom()">Join</button>
</body>
For example, here I attached the trigger to a button. And to make it easier to initially test adding users to rooms, I use Date.now()
as the username. You can open different tabs to serve as different users.
2nd, you need to have a handler for that join
event.
There is an example in the Rooms and Namespaces section of the Flask-SocketIO docs.
@socketio.on("join")
def on_join(data):
user = data["user"]
room = data["room"]
print(f"client {user} wants to join: {room}")
join_room(room)
emit("room_message", f"Welcome to {room}, {user}", room=room)
In the handler, you need to call the join_room
method to add the user to a room under the current namespace. Note that part about the namespace. By default all connections are under the root (/
) namespace. If you have custom namespaces, then each namespace will have their own rooms.
There is also a corresponding leave_room
method.
Here is the complete server-side code:
@socketio.on("connect")
def connect():
print("client wants to connect")
emit("status", { "data": "Connected. Hello!" })
@socketio.on("join")
def on_join(data):
user = data["user"]
room = data["room"]
print(f"client {user} wants to join: {room}")
join_room(room)
emit("room_message", f"Welcome to {room}, {user}", room=room)
Here is the complete client-side code:
<script type="text/javascript" charset="utf-8">
const socket = io();
socket.on("connect", () => {
console.log("connect");
});
socket.on("status", (status) => {
console.log("received status: " + status.data);
});
socket.on("room_message", (msg) => {
console.log("message from room: " + msg);
});
function joinRoom() {
console.log("ask server to join room");
socket.emit("join", { "user": Date.now(), "room": "Notifications" });
}
</script>
<body>
<button onclick="joinRoom()">Join</button>
</body>
Now, you can now open multiple tabs and connect each one to the server. The server-side should show the following messages:
client wants to connect
client wants to connect
client wants to connect
client 1582428076724 wants to join: Notifications
client 1582428080023 wants to join: Notifications
client 1582428082916 wants to join: Notifications
And on the 1st user to join the room (1582428076724), you should be able to see the logs as other users are joining the room.
connect
received status: Connected. Hello!
ask server to join room
message from room: Welcome to Notifications, 1582428076724
message from room: Welcome to Notifications, 1582428080023
message from room: Welcome to Notifications, 1582428082916