# Python WebSocket libraries

Python WebSocket libraries open long-lived, two-way connections between a client and a server. A connection starts as an HTTP request and then carries messages in both directions until either side closes it. These libraries let chat apps, live dashboards, and AI agents stream data without polling.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Starlette](#starlette) | 706.4M | 12.7K | Oct 2026 | BSD-3-Clause |
| [aiohttp](#aiohttp) | 562.2M | 16.6K | Oct 2026 | Apache-2.0 AND MIT |
| [websockets](#websockets) | 539.1M | 5.7K | Oct 2026 | BSD-3-Clause |
| [websocket-client](#websocket-client) | 185.6M | 3.7K | Aug 2026 | Apache-2.0 |
| [Tornado](#tornado) | 122.3M | 22.2K | Nov 2026 | Apache-2.0 |
| [wsproto](#wsproto) | 74.9M | 303 | Nov 2025 | MIT |
| [simple-websocket](#simple-websocket) | 28.7M | 90 | Oct 2024 | MIT |
| [Trio WebSocket](#trio-websocket) | 27.8M | 81 | Feb 2025 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[websockets](#websockets) has the most monthly downloads among the dedicated WebSocket libraries in this comparison, at 539.1M.

## Capabilities

| Library | Client API | Server API |
| --- | --- | --- |
| [Starlette](#starlette) | No | Yes |
| [aiohttp](#aiohttp) | Yes | Yes |
| [websockets](#websockets) | Yes | Yes |
| [websocket-client](#websocket-client) | Yes | No |
| [Tornado](#tornado) | Yes | Yes |
| [wsproto](#wsproto) | Yes | Yes |
| [simple-websocket](#simple-websocket) | Yes | Yes |
| [Trio WebSocket](#trio-websocket) | Yes | Yes |

## Libraries

### Starlette

[GitHub](https://github.com/Kludex/starlette) · [PyPI](https://pypi.org/project/starlette) · [Docs](https://api.github.com/repos/encode/starlette/contents/docs/websockets.md)

Provides a small ASGI library.

- Downloads / mo: 706.4M
- Stars: 12.7K
- Last release: 1.10.0
- License: BSD-3-Clause
- Capabilities: [From the Starlette docs](https://api.github.com/repos/encode/starlette/contents/docs/websockets.md)

```sh
python3 -m pip install starlette
```

**fastapi/fastapi** (104.9K stars)

[fastapi/fastapi](https://github.com/fastapi/fastapi) 

```python
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

```

[docs_src/websockets_/tutorial003.py](https://github.com/fastapi/fastapi/blob/05e6df7e906c3decba377c37548019973f40bf15/docs_src/websockets_/tutorial003.py#L71-L81) · [More projects using Starlette →](https://dashboard.exa.ai/playground/search?q=starlette%20GitHub%20projects)

**Quickstart**

```python
from starlette.websockets import WebSocket
async def app(scope, receive, send):
    websocket = WebSocket(scope=scope, receive=receive, send=send)
    await websocket.accept()
    await websocket.send_text('Hello, world!')
    await websocket.close()

```

From [websockets.md](https://api.github.com/repos/encode/starlette/contents/docs/websockets.md)

### aiohttp

[GitHub](https://github.com/aio-libs/aiohttp) · [PyPI](https://pypi.org/project/aiohttp) · [Docs](https://docs.aiohttp.org/en/stable/client_reference.html)

Provides an asyncio HTTP client and server framework.

- Downloads / mo: 562.2M
- Stars: 16.6K
- Last release: 3.14.5
- License: Apache-2.0 AND MIT
- Capabilities: [From the aiohttp docs](https://docs.aiohttp.org/en/stable/client_reference.html)

```sh
python3 -m pip install aiohttp
```

**Comfy-Org/ComfyUI** (147.6K stars)

[Comfy-Org/ComfyUI](https://github.com/Comfy-Org/ComfyUI) 

```python
async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    sid = request.rel_url.query.get('clientId', '')
    if sid:
        # Reusing existing session, remove old
        self.sockets.pop(sid, None)
    else:
        sid = uuid.uuid4().hex

    # Store WebSocket for backward compatibility
    self.sockets[sid] = ws
    # Store metadata separately
    self.sockets_metadata[sid] = {"feature_flags": {}}

    try:
        # Send initial state to the new client
        await self.send("status", {"status": self.get_queue_info(), "sid": sid}, sid)
        # On reconnect if we are the currently executing client send the current node
        if self.client_id == sid and self.last_node_id is not None:
            await self.send("executing", { "node": self.last_node_id }, sid)

        # Flag to track if we've received the first message
        first_message = True

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.ERROR:
                logging.warning('ws connection closed with exception %s' % ws.exception())
            elif msg.type == aiohttp.WSMsgType.TEXT:
                try:
                    data = json.loads(msg.data)
                    # Check if first message is feature flags
                    if first_message and data.get("type") == "feature_flags":
                        # Store client feature flags
                        client_flags = data.get("data", {})
                        self.sockets_metadata[sid]["feature_flags"] = client_flags

                        # Send server feature flags in response
                        await self.send(
                            "feature_flags",
                            feature_flags.get_server_features(),
                            sid,
                        )

                        logging.debug(
                            f"Feature flags negotiated for client {sid}: {client_flags}"
                        )
                    first_message = False
                except json.JSONDecodeError:
                    logging.warning(
                        f"Invalid JSON received from client {sid}: {msg.data}"
                    )
                except Exception as e:
                    logging.error(f"Error processing WebSocket message: {e}")
    finally:
        self.sockets.pop(sid, None)
        self.sockets_metadata.pop(sid, None)
    return ws

```

[server.py](https://github.com/Comfy-Org/ComfyUI/blob/d5d59c4011312df6b3a4241fb48c045289ad9441/server.py#L337-L394) · [More projects using aiohttp →](https://dashboard.exa.ai/playground/search?q=aiohttp%20GitHub%20projects)

**Quickstart**

```python
import asyncio
import aiohttp
async def main():
    async with aiohttp.ClientSession() as session:
        async with session.ws_connect('ws://localhost:8765') as ws:
            await ws.send_str('hello')
asyncio.run(main())

```

From [client_quickstart.html](https://docs.aiohttp.org/en/stable/client_quickstart.html)

### websockets

[GitHub](https://github.com/python-websockets/websockets) · [PyPI](https://pypi.org/project/websockets) · [Docs](https://api.github.com/repos/python-websockets/websockets/contents/README.rst)

Builds WebSocket servers and clients in Python.

- Downloads / mo: 539.1M
- Stars: 5.7K
- Last release: 17.4
- License: BSD-3-Clause
- Capabilities: [From the websockets docs](https://api.github.com/repos/python-websockets/websockets/contents/README.rst)

**Strengths**

- **Offers async and threaded interfaces.** Choose a coroutine-based or threaded connection API for the application.
- **Retries transient connection failures.** Use the asynchronous connect iterator for reconnects with exponential backoff.

**Watch out for**

- **Receives must stay serialized.** Have one coroutine receive messages from each connection at a time.
- **Directly awaited connections need closing.** Close a directly awaited connection when the application finishes using it.

```sh
python3 -m pip install websockets
```

**Kludex/uvicorn** (11.1K stars)

[Kludex/uvicorn](https://github.com/Kludex/uvicorn) 

```python
def send_keepalive_ping(self) -> None:
    self.ping_timer = None
    if self.close_sent or self.transport.is_closing():  # pragma: no cover
        return
    # Random 4-byte payload identifies this ping; `handle_pong` uses it to ignore stale or unsolicited pongs.
    # See https://github.com/python-websockets/websockets/blob/4d229bf9f583d593aa103287aee0a77c9fbc3a79/src/websockets/asyncio/connection.py#L624
    self.pending_ping_payload = struct.pack("!I", random.getrandbits(32))
    self.ping_sent_at = self.loop.time()
    self.conn.send_ping(self.pending_ping_payload)
    self.transport.write(b"".join(self.conn.data_to_send()))
    if self.ping_timeout is not None:
        self.pong_timer = self.loop.call_later(self.ping_timeout, self.keepalive_timeout)
    else:  # pragma: no cover
        self.schedule_ping()

```

[uvicorn/protocols/websockets/websockets_sansio_impl.py](https://github.com/Kludex/uvicorn/blob/a99c1b76ee9caea67ff98e2ccc457bd372db193f/uvicorn/protocols/websockets/websockets_sansio_impl.py#L343-L356) · [More projects using websockets →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20websockets%20for%20keepalive%20deadlines%2C%20handshake%20rejection%2C%20configured%20TLS%20connections%20and%20protocol%20transport%20integration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```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():
    server = await serve(echo, "localhost", 8765)
    await server.serve_forever()
asyncio.run(main())

```

From [README.rst](https://github.com/python-websockets/websockets/blob/main/README.rst)

### websocket-client

[GitHub](https://github.com/websocket-client/websocket-client) · [PyPI](https://pypi.org/project/websocket-client) · [Docs](https://pypi.org/pypi/websocket-client/1.9.2/json)

Provides low-level WebSocket client APIs and callback-based long-lived connections.

- Downloads / mo: 185.6M
- Stars: 3.7K
- Last release: 1.9.2
- License: Apache-2.0
- Capabilities: [From the websocket-client docs](https://pypi.org/pypi/websocket-client/1.9.2/json)

**Strengths**

- **Handles long-lived callback connections.** Attach message, error, and close callbacks to WebSocketApp.
- **Reconnects through its built-in dispatcher.** Set a reconnect delay on run_forever for automatic retries.

**Watch out for**

- **Compression needs a different client.** Choose another client when the peer requires permessage-deflate.
- **Asyncio needs another integration.** Choose a native asyncio client for coroutine-based applications.

```sh
python3 -m pip install websocket-client
```

**kubernetes-client/python** (7.7K stars)

[kubernetes-client/python](https://github.com/kubernetes-client/python) 

```python
def create_websocket(configuration, url, headers=None):
    enableTrace(False)

    # We just need to pass the Authorization, ignore all the other
    # http headers we get from the generated code
    header = []
    if headers and 'authorization' in headers:
            header.append("authorization: %s" % headers['authorization'])
    if headers and 'sec-websocket-protocol' in headers:
        header.append("sec-websocket-protocol: %s" %
                      headers['sec-websocket-protocol'])
    else:
        header.append("sec-websocket-protocol: %s,%s" % (V5_CHANNEL_PROTOCOL, V4_CHANNEL_PROTOCOL))

    if url.startswith('wss://') and configuration.verify_ssl:
        ssl_opts = {
            'cert_reqs': ssl.CERT_REQUIRED,
            'ca_certs': configuration.ssl_ca_cert or certifi.where(),
        }
        if configuration.assert_hostname is not None:
            ssl_opts['check_hostname'] = configuration.assert_hostname
    else:
        ssl_opts = {'cert_reqs': ssl.CERT_NONE}

    if configuration.cert_file:
        ssl_opts['certfile'] = configuration.cert_file
    if configuration.key_file:
        ssl_opts['keyfile'] = configuration.key_file
    if configuration.tls_server_name:
        ssl_opts['server_hostname'] = configuration.tls_server_name

    websocket = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False)
    connect_opt = {
         'header': header
    }

    if configuration.proxy or configuration.proxy_headers:
        connect_opt = websocket_proxycare(connect_opt, configuration, url, headers)

    websocket.connect(url, **connect_opt)
    return websocket

```

[kubernetes/stream/ws_client.py](https://github.com/kubernetes-client/python/blob/a687381d746b91a6e0f49f7ec357320bcbf4cd38/kubernetes/stream/ws_client.py#L546-L586) · [More projects using websocket-client →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20websocket-client%20for%20keepalive%20deadlines%2C%20handshake%20rejection%2C%20configured%20TLS%20connections%20and%20protocol%20transport%20integration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from websocket import create_connection
ws = create_connection("ws://echo.websocket.events/")
print(ws.recv())
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()

```

From [README.md](https://github.com/websocket-client/websocket-client/blob/master/README.md)

### Tornado

[GitHub](https://github.com/tornadoweb/tornado) · [PyPI](https://pypi.org/project/tornado) · [Docs](https://www.tornadoweb.org/en/stable/websocket.html)

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

- Downloads / mo: 122.3M
- Stars: 22.2K
- Last release: 6.6.1
- License: Apache-2.0
- Capabilities: [From the Tornado docs](https://www.tornadoweb.org/en/stable/websocket.html)

```sh
python3 -m pip install tornado
```

**jupyter-server/jupyter_server** (573 stars)

[jupyter-server/jupyter_server](https://github.com/jupyter-server/jupyter_server) 

```python
def send_ping(self):
    """send a ping to keep the websocket alive"""
    if self.ws_connection is None and self.ping_callback is not None:
        self.ping_callback.stop()
        return

    if self.ws_connection.client_terminated:
        self.close()
        return

    # check for timeout on pong.  Make sure that we really have sent a recent ping in
    # case the machine with both server and client has been suspended since the last ping.
    now = ioloop.IOLoop.current().time()
    since_last_pong = 1e3 * (now - self.last_pong)
    since_last_ping = 1e3 * (now - self.last_ping)
    if since_last_ping < 2 * self.ping_interval and since_last_pong > self.ping_timeout:
        self.log.warning("WebSocket ping timeout after %i ms.", since_last_pong)
        self.close()
        return

    self.ping(b"")
    self.last_ping = now

```

[jupyter_server/base/websocket.py](https://github.com/jupyter-server/jupyter_server/blob/c4c5a51d2cf77d31a266376582ee05c4d661ad4b/jupyter_server/base/websocket.py#L161-L182) · [More projects using Tornado →](https://dashboard.exa.ai/playground/search?q=tornado%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from tornado.websocket import websocket_connect
async def main():
    connection = await websocket_connect('ws://localhost:8765')
    await connection.write_message('hello')
    connection.close()
asyncio.run(main())

```

From [websocket.html](https://www.tornadoweb.org/en/stable/websocket.html)

### wsproto

[GitHub](https://github.com/python-hyper/wsproto) · [PyPI](https://pypi.org/project/wsproto) · [Docs](https://api.github.com/repos/python-hyper/wsproto/contents/docs/source/basic-usage.rst)

Implements WebSocket protocol state and frame handling without owning network I/O.

- Downloads / mo: 74.9M
- Stars: 303
- Last release: 1.3.2
- License: MIT
- Capabilities: [From the wsproto docs](https://api.github.com/repos/python-hyper/wsproto/contents/docs/source/basic-usage.rst)

**Strengths**

- **Fits custom network transports.** Embed the protocol state machine in the application’s own transport.
- **Supports client and server roles.** Use the same protocol class for either end of a WebSocket connection.

**Watch out for**

- **Network I/O stays application-owned.** Provide the code that reads and writes bytes on the actual connection.

```sh
python3 -m pip install wsproto
```

**Kludex/uvicorn** (11.1K stars)

[Kludex/uvicorn](https://github.com/Kludex/uvicorn) 

```python
def send_500_response(self) -> None:
    if self.response_started or self.handshake_complete:
        return  # we cannot send responses anymore
    headers: list[tuple[bytes, bytes]] = [
        (b"content-type", b"text/plain; charset=utf-8"),
        (b"connection", b"close"),
        (b"content-length", b"21"),
    ]
    output = self.conn.send(wsproto.events.RejectConnection(status_code=500, headers=headers, has_body=True))
    output += self.conn.send(wsproto.events.RejectData(data=b"Internal Server Error"))
    self.transport.write(output)

```

[uvicorn/protocols/websockets/wsproto_impl.py](https://github.com/Kludex/uvicorn/blob/a99c1b76ee9caea67ff98e2ccc457bd372db193f/uvicorn/protocols/websockets/wsproto_impl.py#L348-L358) · [More projects using wsproto →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20wsproto%20for%20keepalive%20deadlines%2C%20handshake%20rejection%2C%20configured%20TLS%20connections%20and%20protocol%20transport%20integration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from wsproto import WSConnection, ConnectionType
from wsproto.events import Request

```

From [synchronous_client.py](https://api.github.com/repos/python-hyper/wsproto/contents/README.rst)

### simple-websocket

[GitHub](https://github.com/miguelgrinberg/simple-websocket) · [PyPI](https://pypi.org/project/simple-websocket) · [Docs](https://simple-websocket.readthedocs.io/en/latest/api.html)

Provides a WebSocket server and client for Python.

- Downloads / mo: 28.7M
- Stars: 90
- Last release: 1.1.0
- License: MIT
- Capabilities: [From the simple-websocket docs](https://simple-websocket.readthedocs.io/en/latest/api.html)

```sh
python3 -m pip install simple-websocket
```

**miguelgrinberg/flask-sock** (318 stars)

[miguelgrinberg/flask-sock](https://github.com/miguelgrinberg/flask-sock) 

```python
@wraps(f)
def websocket_route(*args, **kwargs):  # pragma: no cover
    ws = Server(request.environ, **current_app.config.get(
        'SOCK_SERVER_OPTIONS', {}))
    try:
        f(ws, *args, **kwargs)
    except ConnectionClosed:
        pass
    try:
        ws.close()
    except:  # noqa: E722
        pass

    class WebSocketResponse(Response):
        def __call__(self, *args, **kwargs):
            if ws.mode == 'eventlet':
                try:
                    from eventlet.wsgi import WSGI_LOCAL
                    ALREADY_HANDLED = []
                except ImportError:
                    from eventlet.wsgi import ALREADY_HANDLED
                    WSGI_LOCAL = None

                if hasattr(WSGI_LOCAL, 'already_handled'):
                    WSGI_LOCAL.already_handled = True
                return ALREADY_HANDLED
            elif ws.mode == 'gunicorn':
                raise StopIteration()
            elif ws.mode == 'werkzeug':
                return super().__call__(*args, **kwargs)
            else:
                return []

    return WebSocketResponse()

```

[src/flask_sock/__init__.py](https://github.com/miguelgrinberg/flask-sock/blob/bbc58f0d03b4d8e2793933a597200892c46c8ac1/src/flask_sock/__init__.py#L57-L90) · [More projects using simple-websocket →](https://dashboard.exa.ai/playground/search?q=simple-websocket%20GitHub%20projects)

**Quickstart**

```python
from simple_websocket import Client
ws = Client.connect('ws://localhost:5000/echo')
ws.send('hello')
ws.close()

```

From [intro.html](https://simple-websocket.readthedocs.io/en/latest/intro.html)

### Trio WebSocket

[GitHub](https://github.com/python-trio/trio-websocket) · [PyPI](https://pypi.org/project/trio-websocket) · [Docs](https://api.github.com/repos/python-trio/trio-websocket/contents/README.md)

Provides WebSocket support for Trio.

- Downloads / mo: 27.8M
- Stars: 81
- Last release: 0.12.2
- License: MIT
- Capabilities: [From the Trio WebSocket docs](https://api.github.com/repos/python-trio/trio-websocket/contents/README.md)

```sh
python3 -m pip install trio-websocket
```

**SeleniumHQ/selenium** (34.6K stars)

[SeleniumHQ/selenium](https://github.com/SeleniumHQ/selenium) 

```python
async def execute(self, cmd: Generator[dict, T, Any]) -> T:
    """Execute a command on the server and wait for the result.

    Args:
        cmd: any CDP command

    Returns:
        a CDP result
    """
    cmd_id = next(self.id_iter)
    cmd_event = trio.Event()
    self.inflight_cmd[cmd_id] = cmd, cmd_event
    request = next(cmd)
    request["id"] = cmd_id
    if self.session_id:
        request["sessionId"] = self.session_id
    request_str = json.dumps(request)
    if logger.isEnabledFor(logging.DEBUG):
        logger.debug(f"Sending CDP message: {cmd_id} {cmd_event}: {request_str}")
    try:
        await self.ws.send_message(request_str)
    except WsConnectionClosed as wcc:
        raise CdpConnectionClosed(wcc.reason) from None
    await cmd_event.wait()
    response = self.inflight_result.pop(cmd_id)
    if logger.isEnabledFor(logging.DEBUG):
        logger.debug(f"Received CDP message: {response}")
    if isinstance(response, Exception):
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug(f"Exception raised by {cmd_event} message: {type(response).__name__}")
        raise response
    return response

```

[py/private/cdp.py](https://github.com/SeleniumHQ/selenium/blob/700f5ee1012c3105bedacaca65029749a4e5275a/py/private/cdp.py#L201-L232) · [More projects using Trio WebSocket →](https://dashboard.exa.ai/playground/search?q=trio-websocket%20GitHub%20projects)

**Quickstart**

```python
import trio
from sys import stderr
from trio_websocket import open_websocket_url
async def main():
    try:
        async with open_websocket_url('wss://echo.websocket.org') as ws:
            await ws.send_message('hello world!')
            message = await ws.get_message()
            print('Received message: %s' % message)
    except OSError as ose:
        print('Connection attempt failed: %s' % ose, file=stderr)
trio.run(main)

```

From [README.md](https://api.github.com/repos/python-trio/trio-websocket/contents/README.md)

## FAQ

### Which Python WebSocket library should I use?

[websockets](#websockets) suits servers and clients that use asyncio or threads. [websocket-client](#websocket-client) suits callback-based client connections outside asyncio. [wsproto](#wsproto) suits custom transports that own their network I/O.

### How do I build a WebSocket server in Python?

[websockets](#websockets) builds WebSocket servers and clients with coroutine-based or threaded APIs. Only one coroutine at a time should receive messages from each connection.

### Does websockets reconnect automatically?

Its asynchronous connect iterator retries transient connection failures with exponential backoff.

### What is websocket-client?

[websocket-client](#websocket-client) provides low-level WebSocket client APIs and callback-based long-lived connections. Applications built on asyncio need a native asyncio client instead.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python WebSocket libraries websockets websocket-client python-socketio wsproto asyncio server client code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
