Skip to content
Advertisement

How to separate the socketio connection by the path of the URL in my flask chat app

I am trying to build a chat app using Flask-socketio, where clubs can have their members talk to each other. The app differentiates the chats of different clubs using arguments in the URL, as shown in the “/chat/<club_code>” route. However, the socketio connection is updating both chats with the messages of both clubs (club1 and club2). How do I make it so messages sent in “/chat/club1” can only be seen by people on that particular route, and messages sent in “/chat/club2” can only be seen by people on that particular route.

Frontend code:

JavaScript

Backend code:

JavaScript

What is happening now.

Advertisement

Answer

You can store the club code in the session, then use rooms to only send the message to users in a certain club.

JavaScript

When the user loads the page, the club_code session variable is set. When the connect event occurs, the user is joined into a room for their club_code. Then you can use the to parameter of the send method to send the message to the relevant club. See the socket.io and flask-socketio docs about rooms for more information.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement