Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Python Land
  • Python Tutorial
  • Courses
  • Blog
  • Contact
  • Log in
Home » Blog » Python WebSockets: Build a Real-Time Server and Client
A radio mast on a server broadcasts the same score update to three phones, under broadcast(viewers, "Score #3")

Python WebSockets: Build a Real-Time Server and Client

By Erik van Baaren · November 18, 2026

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.

Table of Contents

  • 1. What is a WebSocket?
  • 2. How to install the Python websockets library
  • 3. A Python WebSocket echo server
  • 4. A Python WebSocket client
  • 5. Broadcasting to many clients
  • 6. Handling closed connections
  • 7. Security in one paragraph
  • 8. Keep learning

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.

Erik van Baaren

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

More about Erik

Try this yourself, right now

Run a WebSocket server in a few lines

The same topic as an interactive lesson: short explanation, then code you run and change in your browser, with instant feedback.

Open the interactive lesson

Free to start. Certificates and AI help with Guided.

Monty, your Python learning guide, smiling and waving

Leave a Comment Cancel reply

You must be logged in to post a comment.

Subscribe to my newsletter for Python news, tips, and tricks!

Footer subscribe

  • Home
  • Python Courses
  • Privacy Policy
  • About Us
  • Contact us
©2026 Python Land - All rights reserved
Python Land is not affiliated with Python.org or the Python Software Foundation
  • Free Tutorial
    • Install Python
      • Online Python Interpreter
      • How To Open Python on Windows, Mac, Linux
    • Introduction to Python
      • The Python REPL
      • Python Variable
      • Python String
      • Python Print function
      • Python Booleans
      • For-loop and While-loop
      • Python Functions
      • Your First Python Program
      • Python Comments
    • Creating Python Programs
      • The Best Python IDE
      • Installing VSCode
      • VSCode Python Extensions
      • VSCode GUI Tour
      • Python in VSCode: Running and Debugging
    • Classes and Objects in Python
      • Python Constructor
      • Python Inheritance
    • Structure Your Project
      • Python Modules And Importing
      • Python Packages
    • Python Data Types
      • Python Integer
      • Python Float
      • Python Tuple
      • Python List
      • Python Set
      • Python Dictionary
    • Language Deep Dives
      • Python Try Except (Exceptions)
      • Python Functions: Advanced Concepts
      • List Comprehension
      • Python Iterator
      • Python Range
      • Python Docstrings
      • Python pass (Do Nothing)
    • Interaction with the OS
      • Python Read And Write File
      • Python Subprocess: Run External Commands
    • Venvs / Package Management
      • Working With Python’s venv
      • Pip install: the Python package manager
      • Python Poetry: Package and venv Management Made Easy
      • Python Pipenv: Another Package Manager
      • Pipx: Safely Install Packages Globally
    • Python Concurrency
      • The Python GIL (Global Interpreter Lock)
      • Setting the Baseline
      • Python Threading
      • Python Multiprocessing
    • Data Processing with Python
      • Working With JSON
        • JMESPath Python: JSON Query Language
      • Python YAML: How to Load, Read, and Write YAML
      • Python CSV: Read And Write CSV Files
    • Migrating From Python 2 to 3
      • Check Python Version On The Command-Line
      • How to Migrate To Python 3
      • Python 3 Advantages
    • Using The Unix Shell
      • Basic Linux Commands
      • Bash Scripts
      • Using the Find Command in Linux
      • Unix Pipes
      • Process and Highlight JSON with jq
      • Using the Bash History
      • Bash Multiprocessing
    • Deployment
      • PyInstaller: Create An Executable From Python Code
      • How To Use Docker To Containerize Your Python Project
      • Automatically Build and Deploy Your Python Application with CI/CD
      • Guerrilla Scale Your Web Application
    • Data Science
      • Jupyter Notebook
      • NumPy: Getting Started Tutorial
    • Python Learning Resources
  • Python Courses
  • Blog
  • Login / Register