websockets: A Python Library for WebSocket Servers and Clients

websockets: A Python Library for WebSocket Servers and Clients

Summary

websockets is a robust Python library designed for building WebSocket servers and clients with a focus on correctness, simplicity, robustness, and performance. It leverages Python's `asyncio` framework for an elegant coroutine-based API, also offering `threading` and Sans-I/O implementations. This library provides a reliable foundation for real-time communication in Python applications.

Repository Info

Updated on April 18, 2026
View on GitHub

Tags

Click on any tag to explore related repositories

Introduction

websockets is a robust Python library designed for building WebSocket servers and clients. It emphasizes correctness, simplicity, robustness, and performance, providing an elegant coroutine-based API built on Python's standard asynchronous I/O framework, asyncio. It also offers threading and Sans-I/O implementations for different use cases.

Installation

To get started with websockets, you can install it using pip:

pip install websockets

Examples

Here's an echo server using the asyncio API:

#!/usr/bin/env python

import asyncio
from websockets.asyncio.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765) as server:
        await server.serve_forever()

asyncio.run(main())

And here's how a client sends and receives messages with the threading API:

#!/usr/bin/env python

from websockets.sync.client import connect

def hello():
    with connect("ws://localhost:8765") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")

hello()

Why use websockets?

The websockets library is developed with four core principles in mind:

  • Correctness: websockets is heavily tested for compliance with RFC 6455. Continuous integration ensures 100% branch coverage.
  • Simplicity: It offers a straightforward API, allowing developers to focus on application logic while it manages connections.
  • Robustness: Built for production environments, websockets is known for correctly handling backpressure, a critical aspect in asynchronous programming.
  • Performance: Memory usage is optimized and configurable. A C extension accelerates expensive operations, pre-compiled for Linux, macOS, and Windows, and packaged in the wheel format for each system and Python version.

Links

Find more information and contribute to the websockets project: