An implementation of the WebSocket Protocol (RFC 6455 & 7692)
npx @tessl/cli install tessl/pypi-websockets@15.0.0A 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.
pip install websocketsimport websocketsAsyncio WebSocket operations:
from websockets import connect, serve, broadcast
from websockets import ClientConnection, ServerConnection, ServerSynchronous WebSocket operations:
from websockets.sync import connect, serve
from websockets.sync import ClientConnection, ServerConnection, ServerException handling:
from websockets import (
ConnectionClosed, ConnectionClosedError, ConnectionClosedOK,
InvalidHandshake, ProtocolError, WebSocketException
)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())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())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()The websockets library follows a layered architecture:
Protocol, ClientProtocol, ServerProtocol)asyncio.*, sync.*)ClientConnection, ServerConnection, Server)This design provides flexibility to use WebSocket functionality in different contexts while maintaining protocol correctness and enabling custom extensions.
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]: ...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: ...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]: ...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: ...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"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: ...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): ...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 = 1002WebSocket 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: ...# 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