Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 72 ยท Advanced

Real-Time Apps with WebSockets (Flask-SocketIO)

Build real-time Flask features with Flask-SocketIO. Learn events, emit and broadcast, rooms, acknowledgements, the browser client, and how to test a chat server without a browser.

HTTP is a question-and-answer protocol: the browser asks, the server replies, and the conversation ends. That is perfect for pages, but awkward for a chat window, a live scoreboard or a progress bar, where the server has news and wants to tell the browser now. WebSockets keep one connection open so either side can send messages at any time.

Flask-SocketIO brings the Socket.IO protocol to Flask. Socket.IO is built on WebSockets (with automatic fallbacks) and adds the pieces you would otherwise write yourself: named events, rooms, automatic reconnection and acknowledgements. In this lesson you will write event handlers, send messages to one client, to everyone, and to a room, and test it all from Python.

Flask-SocketIO needs a server that understands long-lived connections. flask run works for learning, but production uses an async worker such as eventlet or gevent, or the threading mode with a WebSocket-capable server such as Werkzeug with simple-websocket. Plain gunicorn sync workers cannot hold the connections.

Events instead of routes

With routes, the URL and HTTP method decide which function runs. With Socket.IO, the event name does. A client calls socket.emit("chat", payload); the server runs the function registered with @socketio.on("chat"). Messages travel in both directions, and either side can emit any event name it likes.

sequenceDiagram
    participant A as Browser A
    participant S as Flask-SocketIO server
    participant B as Browser B
    A->>S: connect
    S-->>A: event "server_hello"
    A->>S: emit "chat" {text: "hi"}
    S-->>A: emit "chat" (broadcast)
    S-->>B: emit "chat" (broadcast)

One persistent connection per browser tab; the server can push to any of them at any time.

Your first handlers

Create a SocketIO object around your app and register handlers. Three kinds of event are built in: connect, disconnect and unnamed messages (message). Everything else uses names you invent.

Inside a handler, emit(event, data) replies to the client that sent the message. broadcast=True sends to every connected client. request.sid identifies the current connection.

The example runs entirely in Python: socketio.test_client(app) behaves like a connected browser and collects what the server sends.

Python Connect, reply and broadcast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Bob never asked for anything, yet he received Ada's message. That is the whole point of broadcasting. Notice that the handler trims and defaults the data it receives: a socket event is user input exactly like a form field, so validate it.

Rooms: send to a group

Broadcasting to everyone is rarely what you want. A room is a named group of connections. join_room("lobby") adds the current client, leave_room removes it, and emit(..., to="lobby") reaches only the members. Every client is automatically in a private room named after its own sid, which is how you message one specific user. Rooms disappear on their own when the last member leaves.

Python Rooms, include_self and acknowledgements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three details deserve attention:

  • include_self=False skips the sender, handy for "typing" and "someone else said" messages where the sender's page already shows the text.
  • Whatever a handler returns is sent back to the sender as an acknowledgement. The client's emit callback receives it, so it knows the server processed the message.
  • Joining a room is server-side state. Check that the user is allowed in the room before calling join_room; the name in the payload comes from the browser.

The browser side

The browser uses the Socket.IO JavaScript client. The snippet below is a read-only sketch of a chat page; it cannot run in this lesson's sandbox because it needs a live server.

HTML
<ul id="log"></ul>
<form id="form"><input id="msg" autocomplete="off"><button>Send</button></form>

<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<script>
  const socket = io();                       // connects to the page's own origin

  socket.on("chat", (m) => {
    const li = document.createElement("li");
    li.textContent = m.user + ": " + m.text;   // textContent, never innerHTML
    document.getElementById("log").append(li);
  });

  document.getElementById("form").addEventListener("submit", (e) => {
    e.preventDefault();
    const box = document.getElementById("msg");
    socket.emit("chat", { user: "me", text: box.value }, (ack) => console.log(ack));
    box.value = "";
  });
</script>

Always insert received text with textContent. If you used innerHTML, a visitor could send <img src=x onerror=...> to everyone in the room, which is cross-site scripting.

Running the server

At home, run the app with the SocketIO object instead of app.run:

Python
if __name__ == "__main__":
    socketio.run(app, debug=True)

For production install eventlet or gevent and let Flask-SocketIO pick it up, or use gunicorn --worker-class eventlet -w 1 module:app. Use one worker unless you add a message queue (such as Redis) with SocketIO(app, message_queue="redis://"); otherwise a message emitted in one process never reaches clients connected to another.

You can also emit from outside a handler, for example from a background task that finishes a job: call socketio.emit("done", payload, to=room).

Security checklist

  • Authenticate during connect. You can read cookies and the session there, and returning False rejects the connection. A logged-in user's Flask-Login current_user works inside handlers.
  • Restrict allowed origins with cors_allowed_origins, because WebSocket handshakes are not covered by the usual same-origin protections.
  • Validate and size-limit every payload; set max_http_buffer_size.
  • Authorize each action (joining a room, deleting a message) the same way you would for an HTTP route.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Flask-SocketIO, what decides which function handles an incoming message?

    Socket.IO messages carry an event name. The server runs the handler registered for that name, no matter what the connection URL is.
  2. 2. How do you send a message to everybody in the room 'lobby' except the sender?

    to= selects the room and include_self=False leaves out the client that triggered the event.
  3. 3. What happens to the return value of an event handler?

    A handler may return data, which Socket.IO delivers to the callback the client passed to emit.
  4. 4. Why should a production Flask-SocketIO app usually run with one worker unless you add a message queue?

    Connections and rooms live in the memory of the worker that accepted them. A message queue such as Redis lets workers forward emits to each other.

Summary

  • WebSockets keep a connection open so the server can push data; Flask-SocketIO wraps the Socket.IO protocol with named events, rooms and acknowledgements.
  • @socketio.on("name") registers a handler; emit replies, broadcast=True or to=room widens the audience, and include_self=False skips the sender.
  • join_room and leave_room manage groups; each client also has a private room named by its sid.
  • socketio.test_client(app) lets you test real-time logic in Python without a browser.
  • Treat every event payload as untrusted input: validate, authorize, and render with textContent.
  • Run production with an async worker and one process, or add a message queue.

Next: stream data one way, from the server to the browser, using plain HTTP in Streaming Responses and Server-Sent Events.