licence version pyversions tests docs openssf

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance.

Built on top of asyncio, Python’s standard asynchronous I/O framework, it provides an elegant coroutine-based API.

Here’s how a client sends and receives messages:

#!/usr/bin/env python

import asyncio
import websockets

async def hello():
    async with websockets.connect("ws://localhost:8765") as websocket:
        await websocket.send("Hello world!")
        await websocket.recv()


And here’s an echo server:

#!/usr/bin/env python

import asyncio
import websockets

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

async def main():
    async with websockets.serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever


Don’t worry about the opening and closing handshakes, pings and pongs, or any other behavior described in the specification. websockets takes care of this under the hood so you can focus on your application!

Also, websockets provides an interactive client:

$ python -m websockets ws://localhost:8765/
Connected to ws://localhost:8765/.
> Hello world!
< Hello world!
Connection closed: 1000 (OK).

Do you like it? Let’s dive in!