websockets

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.

It supports several network I/O and control flow paradigms:

  1. The primary implementation builds upon asyncio, Python’s standard asynchronous I/O framework. It provides an elegant coroutine-based API. It’s ideal for servers that handle many clients concurrently.

    As of version 13.0, there is a new asyncio implementation.

    The historical implementation in websockets.legacy traces its roots to early versions of websockets. Although it’s stable and robust, it is now considered legacy.

    The new implementation in websockets.asyncio is a rewrite on top of the Sans-I/O implementation. It adds a few features that were impossible to implement within the original design.

    The new implementation will become the default as soon as it reaches feature parity. If you’re using the historical implementation, you should ugrade to the new implementation. It’s usually straightforward.

  2. The threading implementation is a good alternative for clients, especially if you aren’t familiar with asyncio. It may also be used for servers that don’t need to serve many clients.

  3. The Sans-I/O implementation is designed for integrating in third-party libraries, typically application servers, in addition being used internally by websockets.

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):
        await asyncio.get_running_loop().create_future()  # run forever

asyncio.run(main())

Here’s a client using the threading API:

#!/usr/bin/env python

import asyncio
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()

Don’t worry about the opening and closing handshakes, pings and pongs, or any other behavior described in the WebSocket 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!