Yuvaraj Vodiboina
All work
(13)Case studyWeb app

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
app.py
@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)
(01)

The problem

How can browsers in the same room send each other messages without anyone refreshing the page?

(02)

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.

(03)

Under the hood

  1. 01Join formA name and a room
  2. 02Flask sessionRemembers both
  3. 03Socket.IOjoin, text and left
  4. 04The roomMessages to that room only
(04)

Decisions

  1. 01

    Rooms on the server, with join_room and leave_room

    Socket.IO already knows how to send to everyone in a room, so a message is one emit to it.

    Trade-offNo history is kept: you see what’s sent while you’re there.

  2. 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.

(05)

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.
(06)

Built with

PythonFlaskFlask-SocketIOFlask-SessionHTML

Next14 of 16Python, image processing Pencil Sketch A photo turned into a pencil sketch in four steps of image processing, with OpenCV. The same four steps run here, on my photo.Read the case study