or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

asyncio-client.mdasyncio-server.mddata-structures.mdexceptions.mdextensions.mdindex.mdprotocol.mdrouting.mdsync-client.mdsync-server.md
tile.json

tessl/pypi-websockets

An implementation of the WebSocket Protocol (RFC 6455 & 7692)

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/websockets@15.0.x

To install, run

npx @tessl/cli install tessl/pypi-websockets@15.0.0

index.mddocs/

WebSockets

A comprehensive Python library implementing the WebSocket Protocol (RFC 6455 & 7692) with both asynchronous (asyncio) and synchronous (threading) APIs. Provides production-ready WebSocket server and client functionality with extensive protocol support, compression, routing, authentication, and error handling.

Package Information

  • Package Name: websockets
  • Language: Python
  • Version: 15.0.1
  • Installation: pip install websockets
  • Documentation: https://websockets.readthedocs.io/

Core Imports

import websockets

Asyncio WebSocket operations:

from websockets import connect, serve, broadcast
from websockets import ClientConnection, ServerConnection, Server

Synchronous WebSocket operations:

from websockets.sync import connect, serve
from websockets.sync import ClientConnection, ServerConnection, Server

Exception handling:

from websockets import (
    ConnectionClosed, ConnectionClosedError, ConnectionClosedOK,
    InvalidHandshake, ProtocolError, WebSocketException
)

Basic Usage

Asyncio Client

import asyncio
import websockets

async def client_example():
    async with websockets.connect("ws://localhost:8765") as websocket:
        # Send a message
        await websocket.send("Hello, Server!")
        
        # Receive a message
        message = await websocket.recv()
        print(f"Received: {message}")

# Run the client
asyncio.run(client_example())

Asyncio Server

import asyncio
import websockets

async def handler(websocket):
    async for message in websocket:
        print(f"Received: {message}")
        # Echo the message back
        await websocket.send(f"Echo: {message}")

async def server_example():
    async with websockets.serve(handler, "localhost", 8765):
        print("WebSocket server started on ws://localhost:8765")
        await asyncio.Future()  # Run forever

# Run the server
asyncio.run(server_example())

Synchronous Client

from websockets.sync import connect

def sync_client_example():
    with connect("ws://localhost:8765") as websocket:
        # Send a message
        websocket.send("Hello, Server!")
        
        # Receive a message
        message = websocket.recv()
        print(f"Received: {message}")

sync_client_example()

Architecture

The websockets library follows a layered architecture:

  • Sans-I/O Protocol Layer: Core WebSocket protocol implementation (Protocol, ClientProtocol, ServerProtocol)
  • I/O Implementation Layer: Asyncio and synchronous I/O implementations (asyncio.*, sync.*)
  • Connection Management: High-level connection classes (ClientConnection, ServerConnection, Server)
  • Extension System: Modular support for WebSocket extensions like per-message deflate compression
  • Routing System: Integration with werkzeug for URL pattern matching and request routing

This design provides flexibility to use WebSocket functionality in different contexts while maintaining protocol correctness and enabling custom extensions.

Capabilities

Asyncio Client Operations

High-level asyncio-based WebSocket client functionality including connection management, message sending/receiving, and connection lifecycle handling with async context managers and iterators.

async def connect(uri: str, **kwargs) -> ClientConnection: ...
async def unix_connect(path: str, **kwargs) -> ClientConnection: ...

class ClientConnection:
    async def send(self, message: str | bytes) -> None: ...
    async def recv(self) -> str | bytes: ...
    async def close(self, code: int = 1000, reason: str = "") -> None: ...
    async def __aenter__(self) -> ClientConnection: ...
    async def __aexit__(self, *args) -> None: ...
    def __aiter__(self) -> AsyncIterator[str | bytes]: ...

Asyncio Client

Asyncio Server Operations

Complete asyncio-based WebSocket server functionality including server lifecycle management, connection handling, message broadcasting, and authentication support.

async def serve(handler: Callable, host: str, port: int, **kwargs) -> Server: ...
async def unix_serve(handler: Callable, path: str, **kwargs) -> Server: ...
def broadcast(connections: Iterable[ServerConnection], message: str | bytes) -> None: ...
def basic_auth(username: str, password: str) -> Callable: ...

class ServerConnection:
    async def send(self, message: str | bytes) -> None: ...
    async def recv(self) -> str | bytes: ...
    async def close(self, code: int = 1000, reason: str = "") -> None: ...

class Server:
    async def __aenter__(self) -> Server: ...
    async def __aexit__(self, *args) -> None: ...
    def close(self) -> None: ...

Asyncio Server

Synchronous Client Operations

Threading-based synchronous WebSocket client functionality providing blocking operations for environments where asyncio is not suitable or preferred.

def connect(uri: str, **kwargs) -> ClientConnection: ...
def unix_connect(path: str, **kwargs) -> ClientConnection: ...

class ClientConnection:
    def send(self, message: str | bytes) -> None: ...
    def recv(self) -> str | bytes: ...
    def close(self, code: int = 1000, reason: str = "") -> None: ...
    def __enter__(self) -> ClientConnection: ...
    def __exit__(self, *args) -> None: ...
    def __iter__(self) -> Iterator[str | bytes]: ...

Synchronous Client

Synchronous Server Operations

Complete threading-based synchronous WebSocket server functionality for traditional Python applications that don't use asyncio.

def serve(handler: Callable, host: str, port: int, **kwargs) -> Server: ...
def unix_serve(handler: Callable, path: str, **kwargs) -> Server: ...
def basic_auth(username: str, password: str) -> Callable: ...

class ServerConnection:
    def send(self, message: str | bytes) -> None: ...
    def recv(self) -> str | bytes: ...
    def close(self, code: int = 1000, reason: str = "") -> None: ...

class Server:
    def __enter__(self) -> Server: ...
    def __exit__(self, *args) -> None: ...
    def close(self) -> None: ...

Synchronous Server

Protocol Implementation

Sans-I/O WebSocket protocol implementation providing the core WebSocket functionality independent of I/O handling, enabling custom integrations and advanced use cases.

class Protocol:
    def __init__(self, side: Side, **kwargs): ...
    def send(self, message: str | bytes) -> bytes: ...
    def recv(self, data: bytes) -> List[str | bytes]: ...
    def close(self, code: int = 1000, reason: str = "") -> bytes: ...

class ClientProtocol(Protocol): ...
class ServerProtocol(Protocol): ...

class Side(Enum):
    CLIENT = "client"
    SERVER = "server"

class State(Enum):
    CONNECTING = "connecting"
    OPEN = "open"
    CLOSING = "closing"
    CLOSED = "closed"

Protocol Implementation

Routing and URL Handling

WebSocket server routing with werkzeug integration for URL pattern matching, parameter extraction, and request routing to different handlers based on URL patterns.

async def route(router: Router, host: str, port: int, **kwargs) -> Server: ...
async def unix_route(router: Router, path: str, **kwargs) -> Server: ...

class Router:
    def __init__(self): ...
    def route(self, path: str, **kwargs) -> Callable: ...
    def add_route(self, handler: Callable, path: str, **kwargs) -> None: ...

Routing

Exception Handling

Comprehensive exception hierarchy for precise error handling covering connection lifecycle, protocol violations, handshake failures, and validation errors.

class WebSocketException(Exception): ...
class ConnectionClosed(WebSocketException): ...
class ConnectionClosedOK(ConnectionClosed): ...
class ConnectionClosedError(ConnectionClosed): ...
class InvalidHandshake(WebSocketException): ...
class ProtocolError(WebSocketException): ...
class SecurityError(InvalidHandshake): ...
class PayloadTooBig(ProtocolError): ...

Exception Handling

Data Structures and Types

Core data structures for HTTP headers, WebSocket frames, close codes, and type definitions used throughout the WebSocket implementation.

class Headers:
    def __init__(self, *args, **kwargs): ...
    def __getitem__(self, key: str) -> str: ...
    def __setitem__(self, key: str, value: str) -> None: ...
    def get(self, key: str, default: str = None) -> str: ...

class Frame:
    def __init__(self, opcode: Opcode, data: bytes, fin: bool = True): ...

class Opcode(Enum):
    CONT = 0
    TEXT = 1
    BINARY = 2
    CLOSE = 8
    PING = 9
    PONG = 10

class CloseCode(Enum):
    NORMAL_CLOSURE = 1000
    GOING_AWAY = 1001
    PROTOCOL_ERROR = 1002

Data Structures

Extensions and Compression

WebSocket extension system with built-in per-message deflate compression support (RFC 7692) and extensible framework for custom extensions.

def enable_client_permessage_deflate(**kwargs) -> List[ClientExtensionFactory]: ...
def enable_server_permessage_deflate(**kwargs) -> List[ServerExtensionFactory]: ...

class ClientPerMessageDeflateFactory:
    def __init__(self, **kwargs): ...

class ServerPerMessageDeflateFactory:
    def __init__(self, **kwargs): ...

class Extension:
    def encode(self, frame: Frame) -> Frame: ...
    def decode(self, frame: Frame) -> Frame: ...

Extensions

Common Type Definitions

# Type aliases used throughout the API
Data = str | bytes  # WebSocket message content
HeadersLike = Dict[str, str] | List[Tuple[str, str]] | Headers  # Header input formats
Origin = str  # Origin header value
Subprotocol = str  # WebSocket subprotocol name
ExtensionName = str  # WebSocket extension name
ExtensionParameter = Tuple[str, str | None]  # Extension parameter
LoggerLike = logging.Logger | logging.LoggerAdapter  # Logger types
StatusLike = int | HTTPStatus  # HTTP status types