API Reference

websockets

Async WebSocket client and server library for Python built on asyncio with automatic framing.

Official Documentation ↗
CompatibilityThis documentation covers version v17.4. Check the official docs for the latest API surface.

Installation

pippip install websockets

Methods

Overview

websockets provides asyncio-based client and server implementations of the WebSocket protocol, handling the handshake, framing and keepalive so you work with messages instead of bytes.

Core Methods

connect opens a client connection usable with async with, serve starts a server from a handler, and both send and recv are awaitable. Messages can be iterated with async for.

Usage Notes

Manage connections in a registry for broadcasting, handle ConnectionClosed per connection, and apply back-pressure so a slow consumer cannot grow memory without bound.

Common Pitfalls

Ignoring ConnectionClosed leaves dangling handlers. Unbounded send queues from slow clients cause memory growth. Proxies may close idle connections without keepalive, so ping settings matter behind load balancers.

Errors

The official API reference declares the following error types:

Security

Official security statements captured from the package documentation:

  • 生产环境必须使用 TLS(wss)保护 WebSocket 连接 — “In production, you should always secure WebSocket connections with TLS. Secure WebSocket connections provide confidentiality and integrity, as well as better reliability because they reduce the risk of interference by bad proxies.” (source: https://websockets.readthedocs.io/en/stable/topics/security.html, fetched 2026-11-08T16:03:08.4363995+08:00)

API reference evidence

Fetched from official sources on 2026-11-08T16:03:08.4363995+08:00 via WebFetch 官方 API reference(client / server / exceptions / topics/security).

FAQ

How do I handle ping and timeouts?
The library sends keepalive pings and closes on missed pongs. Configure ping_interval and ping_timeout, and catch ConnectionClosed to distinguish normal from abnormal closure.
How do I broadcast to many clients?
Track connected handlers in a set and send to each. Back-pressure matters, so avoid unbounded queues and handle slow consumers by dropping or disconnecting them.
What about TLS?
Use wss URIs and pass an ssl context. Certificate verification is on by default; disabling it exposes clients to interception.