Chat Room
A browser chat with rooms: choose a name and a room, and your messages go only to the people in it. Flask and Socket.IO.
- Platform
- Web app
- When
- 2021
- Role
- Sole developer
- Status
- Earlier work, on GitHub
@socketio.on('join', namespace='/chat')
def join(message):
room = session.get('room')
join_room(room)
emit('status', {'msg': session.get('username') + ' has entered the room.'}, room=room)
@socketio.on('text', namespace='/chat')
def text(message):
room = session.get('room')
emit('message', {'msg': session.get('username') + ' : ' + message['msg']}, room=room)The problem
How can browsers in the same room send each other messages without anyone refreshing the page?
What I built
The /chat route takes a name and a room and keeps both in a Flask session, stored on the server’s filesystem. Socket.IO events in the /chat namespace do the rest: join puts you in the room and tells everyone, text sends your message to that room only, and left takes you out, clears the session and says you’ve gone.
Hard partKnowing who you are and which room you’re in, across a page load and a socket connection.
Under the hood
- 01Join formA name and a room
- 02Flask sessionRemembers both
- 03Socket.IOjoin, text and left
- 04The roomMessages to that room only
Decisions
- 01
Rooms on the server, with
join_roomandleave_roomSocket.IO already knows how to send to everyone in a room, so a message is one
emitto it.Trade-offNo history is kept: you see what’s sent while you’re there.
- 02
One session for the page and the socket
Socket.IO’s own sessions are off, so both read the Flask session that joining sets.
Trade-offSessions live on one server’s disk.
What I learned
- It was a learning prototype: debug mode on, a placeholder secret key, and no history, logins or moderation. Not something to deploy as it is.
Built with
PythonFlaskFlask-SocketIOFlask-SessionHTML