Claude Code for websockets: Async WebSocket Server and Client in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for websockets: Async WebSocket Server and Client in Python
AI

Claude Code for websockets: Async WebSocket Server and Client in Python

Published: April 24, 2028
Read time: 5 min read
By: Claude Skills 360

websockets is a pure-asyncio WebSocket library for building servers and clients. pip install websockets. Server: from websockets.server import serve; async with serve(handler, "localhost", 8765): await asyncio.Future(). Handler: async def handler(ws): msg = await ws.recv(); await ws.send(f"Echo: {msg}"). Client: from websockets.sync.client import connect; with connect("ws://localhost:8765") as ws: ws.send("Hello"); print(ws.recv()). Async client: from websockets.asyncio.client import connect; async with connect("ws://...") as ws: await ws.send("hi"); msg = await ws.recv(). Broadcast: for ws in connected: await ws.send(message). JSON: await ws.send(json.dumps(data)); data = json.loads(await ws.recv()). ConnectionClosed: from websockets.exceptions import ConnectionClosed. Close: await ws.close(code=1000, reason="done"). Ping: await ws.ping(); pong = await ws.ping(). SSL: ssl.SSLContext passed to serve(ssl=ctx). connect(uri, ssl=ctx). Max size: serve(..., max_size=2**20). Compression: serve(..., compression="deflate"). Origin: serve(..., origins=["https://example.com"]). Headers: ws.request.headers. Path: ws.request.path. ws.remote_address. Subprotocol: serve(..., subprotocols=["chat"]). Timeout: async with asyncio.timeout(5): await ws.recv(). websockets.asyncio.server. Claude Code generates websockets echo servers, real-time broadcast systems, and async WebSocket client libraries.

CLAUDE.md for websockets

## websockets Stack
- Version: websockets >= 13.0 | pip install websockets
- Server: async with serve(handler, host, port): await asyncio.Future()
- Handler: async def handler(ws): msg=await ws.recv(); await ws.send(reply)
- Async client: async with connect("ws://host:port/path") as ws: ...
- Sync client: with websockets.sync.client.connect("ws://...") as ws: ...
- JSON: json.dumps/loads around send/recv
- Error: catch ConnectionClosed for graceful disconnect handling

websockets Real-Time Pipeline

# app/ws.py — websockets echo server, broadcast, auth, client, and room manager
from __future__ import annotations

import asyncio
import json
import logging
from typing import Any, Callable, Awaitable

from websockets.asyncio.client import connect
from websockets.asyncio.server import ServerConnection, serve
from websockets.exceptions import ConnectionClosed


log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic echo server
# ─────────────────────────────────────────────────────────────────────────────

async def echo_handler(ws: ServerConnection) -> None:
    """
    Simple echo server handler — reflect every message back.
    Handles text and binary frames; closes cleanly on disconnect.
    """
    remote = ws.remote_address
    log.info("Connected: %s", remote)
    try:
        async for message in ws:
            if isinstance(message, str):
                await ws.send(f"Echo: {message}")
            else:
                await ws.send(message)  # binary echo
    except ConnectionClosed:
        log.info("Disconnected: %s", remote)


async def run_echo_server(host: str = "localhost", port: int = 8765) -> None:
    """Run a WebSocket echo server until interrupted."""
    async with serve(echo_handler, host, port) as server:
        log.info("Echo server on ws://%s:%d", host, port)
        await server.serve_forever()


# ─────────────────────────────────────────────────────────────────────────────
# 2. Broadcast (pub-sub / chat room)
# ─────────────────────────────────────────────────────────────────────────────

class ConnectionHub:
    """
    A hub that tracks connected WebSocket clients and supports broadcasting.

    Usage:
        hub = ConnectionHub()
        async def handler(ws):
            async with hub.connected(ws):
                async for msg in ws:
                    await hub.broadcast(msg, exclude=ws)
    """

    def __init__(self):
        self._connections: set[ServerConnection] = set()

    @property
    def count(self) -> int:
        return len(self._connections)

    async def _add(self, ws: ServerConnection) -> None:
        self._connections.add(ws)

    async def _remove(self, ws: ServerConnection) -> None:
        self._connections.discard(ws)

    class _CM:
        def __init__(self, hub: "ConnectionHub", ws: ServerConnection):
            self._hub = hub
            self._ws  = ws

        async def __aenter__(self):
            await self._hub._add(self._ws)
            return self._ws

        async def __aexit__(self, *_):
            await self._hub._remove(self._ws)

    def connected(self, ws: ServerConnection):
        """Context manager: register ws on enter, deregister on exit."""
        return self._CM(self, ws)

    async def broadcast(
        self,
        message: str | bytes,
        exclude: ServerConnection | None = None,
    ) -> int:
        """
        Send message to all connected clients.
        exclude: skip this connection (e.g. the sender).
        Returns count of successful sends.
        """
        targets = self._connections - ({exclude} if exclude else set())
        sent = 0
        for ws in list(targets):
            try:
                await ws.send(message)
                sent += 1
            except ConnectionClosed:
                self._connections.discard(ws)
        return sent

    async def broadcast_json(self, data: Any, exclude: ServerConnection | None = None) -> int:
        return await self.broadcast(json.dumps(data), exclude=exclude)


# ─────────────────────────────────────────────────────────────────────────────
# 3. JSON message protocol
# ─────────────────────────────────────────────────────────────────────────────

async def send_json(ws: ServerConnection, data: Any) -> None:
    """Send a Python object as JSON."""
    await ws.send(json.dumps(data))


async def recv_json(ws: ServerConnection) -> Any:
    """Receive the next message and parse as JSON."""
    raw = await ws.recv()
    return json.loads(raw)


class JsonProtocol:
    """
    Wrapper for a WebSocket connection with typed message dispatch.

    Usage:
        proto = JsonProtocol(ws)
        await proto.send({"type": "hello", "name": "Alice"})
        msg = await proto.recv()
        if msg["type"] == "ping":
            await proto.send({"type": "pong"})
    """

    def __init__(self, ws: ServerConnection):
        self._ws = ws

    async def send(self, data: Any) -> None:
        await self._ws.send(json.dumps(data))

    async def recv(self) -> Any:
        raw = await self._ws.recv()
        return json.loads(raw)

    async def handle_loop(
        self,
        dispatch: Callable[[Any], Awaitable[Any | None]],
    ) -> None:
        """
        Read messages in a loop, passing each to dispatch(msg).
        If dispatch returns a non-None value, send it back.
        """
        try:
            async for raw in self._ws:
                msg = json.loads(raw)
                reply = await dispatch(msg)
                if reply is not None:
                    await self.send(reply)
        except ConnectionClosed:
            pass


# ─────────────────────────────────────────────────────────────────────────────
# 4. Room-based chat server
# ─────────────────────────────────────────────────────────────────────────────

class ChatRoom:
    """
    Named chat room: join/leave/broadcast with message history.

    Usage:
        room_manager = {room_name: ChatRoom(name)}
        async def ws_handler(ws):
            room = rooms["general"]
            await room.join(ws, username="Alice")
    """

    def __init__(self, name: str, max_history: int = 50):
        self.name = name
        self._members: dict[ServerConnection, str] = {}  # ws → username
        self._history: list[dict] = []
        self._max_history = max_history

    @property
    def member_count(self) -> int:
        return len(self._members)

    async def join(self, ws: ServerConnection, username: str) -> None:
        """Add ws to the room and announce."""
        self._members[ws] = username
        join_msg = {"type": "join", "user": username, "room": self.name}
        await self._broadcast(json.dumps(join_msg), exclude=ws)
        # Send history to the new member
        for msg in self._history:
            try:
                await ws.send(json.dumps(msg))
            except ConnectionClosed:
                break

    async def leave(self, ws: ServerConnection) -> None:
        """Remove ws from the room."""
        username = self._members.pop(ws, "unknown")
        leave_msg = {"type": "leave", "user": username, "room": self.name}
        await self._broadcast(json.dumps(leave_msg))

    async def send_message(self, ws: ServerConnection, text: str) -> None:
        """Broadcast a chat message from ws."""
        username = self._members.get(ws, "anon")
        msg = {"type": "message", "user": username, "room": self.name, "text": text}
        self._history.append(msg)
        if len(self._history) > self._max_history:
            self._history.pop(0)
        await self._broadcast(json.dumps(msg))

    async def _broadcast(self, raw: str, exclude: ServerConnection | None = None) -> None:
        for ws in list(self._members):
            if ws is not exclude:
                try:
                    await ws.send(raw)
                except ConnectionClosed:
                    self._members.pop(ws, None)


# ─────────────────────────────────────────────────────────────────────────────
# 5. Async client helpers
# ─────────────────────────────────────────────────────────────────────────────

async def ws_send_receive(uri: str, messages: list[Any], timeout: float = 5.0) -> list[Any]:
    """
    Connect to uri, send each message (as JSON), collect replies.
    Returns list of parsed JSON responses.
    """
    responses = []
    async with connect(uri) as ws:
        for msg in messages:
            await ws.send(json.dumps(msg))
            try:
                async with asyncio.timeout(timeout):
                    raw = await ws.recv()
                    responses.append(json.loads(raw))
            except TimeoutError:
                break
    return responses


async def ws_subscribe(
    uri: str,
    on_message: Callable[[Any], Awaitable[None]],
    reconnect: bool = True,
    reconnect_delay: float = 2.0,
) -> None:
    """
    Subscribe to a WebSocket stream; call on_message for each JSON message.
    reconnect=True: automatically reconnect on disconnect.
    """
    while True:
        try:
            async with connect(uri) as ws:
                log.info("Subscribed to %s", uri)
                async for raw in ws:
                    await on_message(json.loads(raw))
        except ConnectionClosed as e:
            log.warning("Disconnected from %s: %s", uri, e)
        except Exception as e:
            log.error("Error from %s: %s", uri, e)

        if not reconnect:
            break
        log.info("Reconnecting in %.1fs...", reconnect_delay)
        await asyncio.sleep(reconnect_delay)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

async def demo():
    """Run an in-process echo server + client to verify the setup."""
    import threading

    port = 18765

    async def _server():
        hub = ConnectionHub()
        async def handler(ws):
            async with hub.connected(ws):
                async for msg in ws:
                    await hub.broadcast(msg)

        async with serve(handler, "localhost", port):
            await asyncio.sleep(2)

    # Start server in background task
    server_task = asyncio.create_task(_server())
    await asyncio.sleep(0.1)  # let server start

    print("=== Client send/receive ===")
    replies = await ws_send_receive(
        f"ws://localhost:{port}",
        [{"text": "Hello"}, {"text": "World"}],
    )
    print("Replies:", replies)

    server_task.cancel()
    try:
        await server_task
    except asyncio.CancelledError:
        pass
    print("Demo complete")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(demo())

For the socket.io (python-socketio) alternative — socket.io adds namespaces, rooms, acknowledgements, and automatic reconnect at the protocol level; websockets is lower-level and implements the IETF RFC 6455 WebSocket standard directly — use websockets when you want standards compliance and control over your protocol, socket.io when you need its higher-level abstractions or browser client library. For the FastAPI WebSocket alternative — FastAPI’s built-in WebSocket support (@app.websocket("/ws")) wraps Starlette’s WebSocket and integrates with FastAPI’s dependency injection; the standalone websockets library is better for pure async WebSocket microservices or CLI clients where you don’t need an HTTP framework alongside. The Claude Skills 360 bundle includes websockets skill sets covering echo_handler/run_echo_server(), ConnectionHub broadcast manager, JsonProtocol send/recv/handle_loop(), ChatRoom join/leave/send_message with history, send_json/recv_json helpers, ws_send_receive() client, ws_subscribe() streaming client with auto-reconnect, and in-process demo. Start with the free tier to try WebSocket real-time code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free