Python WebSockets: Build a Real-Time Server and Client

Python WebSockets give your program a connection that stays open, where both the server and the client can send a message at any moment. Most of the web works by asking: your browser sends a request, the server answers, and that’s it. But what if the server has news? A live score, a chat message, a price that just changed. That’s what WebSockets are for.

In this tutorial, you’ll use the popular websockets library to build a WebSocket server and client in Python, then push live updates to several clients at once.

What is a WebSocket?

A WebSocket is a long-lived, two-way connection between a client and a server. It starts life as an ordinary HTTP request with a special header that asks the server to switch protocols. If the server agrees, it answers with status 101 Switching Protocols, and from then on the same TCP connection carries WebSocket messages in both directions.

Compare that with the alternatives:

  • Polling: the client asks “anything new?” every few seconds. Simple, but slow to notice changes and wasteful when nothing happens.
  • Long polling: the client asks, and the server holds the request open until there is news. Better, but every update still costs a new request.
  • WebSockets: one connection, opened once. The server sends updates the moment they happen.

WebSocket addresses start with ws://, or wss:// for the encrypted version, just like http:// and https://.

How to install the Python websockets library

Install websockets with pip, ideally in a virtual environment:

python -m pip install websocketsCode language: Bash (bash)

The examples in this article were tested with websockets 17.4 on Python 3.13. Versions 14 and later use the import paths shown here (websockets.asyncio.server, websockets.sync.client); older tutorials online often use a legacy API that has since been deprecated.

A Python WebSocket echo server

The library’s main API is built on asyncio, Python’s framework for doing many waits at once. Don’t worry if you haven’t used it before: for a server, the pattern is always the same. Save this as server.py:

import asyncio
from websockets.asyncio.server import serve


async def echo(websocket):
    async for message in websocket:
        await websocket.send(f"Echo: {message}")


async def main():
    async with serve(echo, "127.0.0.1", 8765) as server:
        print("Listening on ws://127.0.0.1:8765")
        await server.serve_forever()


asyncio.run(main())Code language: Python (python)

The library calls your handler, echo, once for every client that connects, with a websocket object for that connection. The async for loop receives messages until the client disconnects, and send() sends one back. The handshake, framing and closing are all handled for you.

A Python WebSocket client

A client doesn’t need asyncio at all. The library also has a synchronous client, which is perfect for scripts and tests. Save this as client.py:

from websockets.sync.client import connect

with connect("ws://127.0.0.1:8765") as websocket:
    websocket.send("Hello!")
    print(websocket.recv())Code language: Python (python)

Start the server in one terminal and run the client in another:

$ python client.py
Echo: Hello!Code language: plaintext (plaintext)

The with block closes the connection cleanly when you’re done. If you prefer async code, the asyncio client looks almost the same:

import asyncio
from websockets.asyncio.client import connect


async def main():
    async with connect("ws://127.0.0.1:8765") as websocket:
        for word in ["one", "two", "three"]:
            await websocket.send(word)
            print(await websocket.recv())


asyncio.run(main())Code language: Python (python)
Echo: one
Echo: two
Echo: threeCode language: plaintext (plaintext)

Want to run a server like this without installing anything? Try the free interactive lesson where you run a WebSocket server in a few lines, right in your browser.

Broadcasting to many clients

The echo server only answers. The real power of WebSockets is the server speaking first. Here’s a tiny live scoreboard: every viewer that connects is added to a set, and once a second the server broadcasts an update to all of them:

import asyncio
import itertools
from websockets.asyncio.server import broadcast, serve

viewers = set()


async def viewer(websocket):
    viewers.add(websocket)
    try:
        await websocket.wait_closed()
    finally:
        viewers.discard(websocket)


async def announce_scores():
    for tick in itertools.count(1):
        await asyncio.sleep(1)
        broadcast(viewers, f"Score update #{tick}")


async def main():
    async with serve(viewer, "127.0.0.1", 8766):
        await announce_scores()


asyncio.run(main())Code language: Python (python)

And a viewer that prints the first three updates:

from websockets.sync.client import connect

with connect("ws://127.0.0.1:8766") as websocket:
    for _ in range(3):
        print(websocket.recv())Code language: Python (python)
Score update #1
Score update #2
Score update #3Code language: plaintext (plaintext)

Run two or three viewers at the same time, and they all receive every update. A few details make this robust:

  • The finally block removes a viewer from the set however the connection ends, so the server never keeps sending to a client that’s gone.
  • broadcast() doesn’t wait for slow clients. If one viewer’s network is slow, the others still get their updates on time. That’s exactly the problem you’d hit if you looped over the clients and awaited send() for each one.
  • The handler waits with wait_closed() because viewers only listen. In a chat app, you’d use async for message in websocket here instead.

Handling closed connections

Connections end: users close tabs, phones lose signal, servers restart. When that happens, recv() and send() raise ConnectionClosed. A clean close carries a close code and an optional reason, which you can read from the exception:

from websockets.exceptions import ConnectionClosed
from websockets.sync.client import connect

with connect("ws://127.0.0.1:8765") as websocket:
    websocket.close(code=1000, reason="done")
    try:
        websocket.recv()
    except ConnectionClosed as closed:
        print("closed:", closed.rcvd.code, closed.rcvd.reason)Code language: Python (python)
closed: 1000 doneCode language: plaintext (plaintext)

Code 1000 means a normal close. Codes like 1001 (going away) and 1011 (server error) tell the client whether reconnecting makes sense. A client that should stay connected, like a dashboard, needs a reconnect loop that waits a little longer after each failed attempt.

Security in one paragraph

A WebSocket server is reachable by anyone who can reach its address, so treat it like any web endpoint. Use wss:// in production. Check who’s connecting before you accept them, for example with a token sent during the opening handshake. And check the Origin header if browsers connect to your server, so another website can’t open a connection with your users’ cookies.

Keep learning

You now have a working WebSocket server, a client, and a broadcast that pushes live updates. To understand what the library does for you, our WebSockets with Python course has you perform the handshake and encode every frame yourself, byte by byte, before building a tested, live quiz-night scoreboard with the real library. The websockets documentation is the full reference.

Leave a Comment