Skip to main content

docs Build Status PyPI Downloads PyPI version License Code style: ruff codecov

Webshocket

Webshocket is a lightweight Python framework designed to handle the complexity of WebSocket-based RPC applications. It provides a high-level API for remote procedure calls, per-client session management, and efficient message broadcasting.

Why Webshocket?

Exposing local TCP projects to the internet effectively often requires expensive paid tunnels or unstable free alternatives. Webshocket solves this by running over standard WebSockets, making it natively compatible with robust, free HTTP tunnel services like Cloudflare Argo and LocalTunnel.

It combines the simplicity of raw sockets with a rich feature set for easier development:

  • Free Tunneling: Works out-of-the-box with any HTTP/WebSocket tunnel.
  • Developer Experience: Includes a complete RPC system, session state management, rate limiting, and pub/sub channels, no complex middleware or global state required.

Comparison with Other WebSocket Libraries

Feature Webshocket websockets socket.io FastAPI WS
RPC Layer ✅ Built-in ❌ Manual ⚠ Client-driven ❌ Manual
Streaming RPC ✅ Built-in ❌ Manual ❌ Manual ❌ Manual
Session State ✅ Connection attrs ❌ Manual ✅ Rooms ❌ Manual
Predicates/Auth ✅ Built-in ❌ Manual ⚠ Library-dependent ❌ Manual
Pub/Sub Channels ✅ Built-in ❌ Manual ✅ Rooms ❌ Manual
Rate Limiting ✅ Decorator-based ❌ Manual ❌ Manual ⚠ Middleware
Auto-Retry ✅ Built-in (exp. backoff) ❌ Manual ✅ Built-in ❌ Manual
HTTP Tunnels ✅ Designed for ✅ Compatible ⚠ HTTP fallback ✅ Compatible
Cross-Language ✅ Binary + JSON ⚠ Protocol only ✅ Client libs ⚠ Protocol only
Performance Core picows (Cython) Pure Python JS-heavy ASGI stack

Unique Features at a Glance

Webshocket simplifies complex networking logic into simple, object-oriented patterns.

1. Powerful RPC with Access Control

Define server methods effortlessly and protect them with custom rules (predicates).

class MyHandler(webshocket.WebSocketHandler):
    @webshocket.rpc_method(alias_name="add")
    async def add(self, _: webshocket.ClientConnection, a: int, b: int):
        return a + b

    # Unique: Use built-in predicates for clean access control
    @webshocket.rpc_method(requires=webshocket.Is("is_admin"))
    async def secret_function(self, conn: webshocket.ClientConnection):
        return "Sensitive Data"
2. Effortless Session State

No more look-up tables. Assign data directly to the client connection; Webshocket handles the persistence for you.

    @webshocket.rpc_method()
    async def login(self, connection: webshocket.ClientConnection, user_id: str):
        # Direct attribute assignment persists for the session
        connection.user_id = user_id
        connection.is_admin = True

        # Subscribe to updates immediately
        connection.subscribe("broadcast-channel")
3. Decorator-Based Rate Limiting

Protect your RPC methods from abuse with a simple decorator. Supports human-readable periods and optional auto-disconnect.

class MyHandler(webshocket.WebSocketHandler):
    @webshocket.rate_limit(limit=5, period="1m")  # 5 calls per minute
    @webshocket.rpc_method()
    async def expensive_operation(self, connection: webshocket.ClientConnection, query: str):
        return await run_ai_model(query)

    @webshocket.rate_limit(limit=100, period="10s", disconnect_on_limit_exceeded=True)
    @webshocket.rpc_method()
    async def chat_message(self, connection: webshocket.ClientConnection, msg: str):
        return await process_message(msg)
4. Pub/Sub Channels with Wildcard Support

Webshocket supports powerful wildcard subscriptions using glob patterns (*, ?, []). This allows clients to subscribe to a broad category of updates with a single call.

class StockHandler(webshocket.WebSocketHandler):
    @webshocket.rpc_method()
    async def watch_sector(self, connection: webshocket.ClientConnection, sector: str):
        # Client subscribes to a pattern like "tech.*"
        connection.subscribe(f"{sector}.*")

    def broadcast_stock_price(self, symbol: str, price: float):
        # If symbol is "tech.AAPL", it automatically routes to anyone
        # subscribed to "tech.*" OR "tech.AAPL"
        self.publish(symbol, {"price": price})

Smart Filtering (Predicates)

You can also combine subscriptions with Predicates to filter recipients dynamically without creating thousands of sub-channels.

    @webshocket.rpc_method()
    async def join_room(self, connection: webshocket.ClientConnection, room: str, team: str):
        connection.subscribe(room)
        connection.team = team # Persistent session state

    def send_team_update(self, room: str, team: str, data: dict):
        # Only publish to clients in 'room' whose 'team' attribute equals 'team'
        self.publish(room, data, predicate=webshocket.IsEqual("team", team))
5. Auto-Retry with Exponential Backoff

The client handles reconnection automatically, no manual retry loops needed.

async def main():
    client = webshocket.WebSocketClient("ws://your-tunnel.url")
    await client.connect(retry=True, max_retry_attempt=5, retry_interval=2)

    result = await client.send_rpc("add", 10, 20)
    print(result.data)  # 30
6. Integrated Tunnelling & Deployment

Designed to run perfectly behind free HTTP tunnels, making it the easiest way to expose a local AI or IoT project to the world.

async def main():
    server = webshocket.WebSocketServer("0.0.0.0", 5000, clientHandler=MyHandler)
    async with server:
        await server.serve_forever()
7. Cross-Language Compatibility

Webshocket is designed to be language-agnostic. While the Python client is optimized with msgspec, the server natively understands standard JSON packets. This means you can build a client in JavaScript, Java, or C# using nothing but the standard library.

// Example: Standard Browser JavaScript Client
const socket = new WebSocket("ws://your-tunnel.url");

socket.onopen = () => {
	const rpcRequest = {
		rpc: {
			type: "request",
			method: "add",
			args: [10, 20],
			kwargs: {},
		},
		source: 5,
	};

	socket.send(JSON.stringify(rpcRequest));
};

socket.onmessage = async (event) => {
	const packet = JSON.parse(await event.data.text());
	console.log("Result:", packet.rpc.response); // 30
};
8. Streaming RPC

Stream data from server to client in real-time using async generators. The client iterates over chunks as they arrive. This is perfect for AI token streaming, live feeds, or large result sets.

# Server - yield chunks as they're produced
class MyHandler(webshocket.WebSocketHandler):
    @webshocket.rpc_method()
    async def generate_report(self, connection: webshocket.ClientConnection, query: str):
        async for chunk in run_ai_model(query):
            yield chunk  # Each yield sends a packet to the client
# Client - iterate over the stream
async for packet in client.stream_rpc("generate_report", "Summarize Q4 earnings"):
    print(packet.data, end="", flush=True)

Contributing

Contributions are welcome! Please feel free to open an issue or submit a pull request on our GitHub repository.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for webshocket 0.5.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for webshocket 0.5.2
File Size Uploaded Provenance Actions
webshocket-0.5.2.tar.gz 45.9 kB With provenance Details for webshocket-0.5.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for webshocket 0.5.2
File Interpreter ABI Platform Actions
webshocket-0.5.2-py3-none-any.whl Python 3 none any Details for webshocket-0.5.2-py3-none-any.whl

Total release size: 81.3 kB

Release files / webshocket-0.5.2.tar.gz

Download URL webshocket-0.5.2.tar.gz
Size 45.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ce027c9b86da78692d80e96b46e5eb9e4bf8b97f939f9696d438c4068fa55fe4
BLAKE2b-256 checksum
How to use checksums
645f93deac7db59dca229eebe9a801a1cc96cc6eec51bf7f405b6d14a663417f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 17, 2026.

Transparency log

Release files / webshocket-0.5.2-py3-none-any.whl

Download URL webshocket-0.5.2-py3-none-any.whl
Size 35.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4ce4cd86766f64bde10f3220c01753f43ac3052ec9cb6802513f8cbaaebde5b1
BLAKE2b-256 checksum
How to use checksums
38d2f3f7e93702a97509adbee163e0145680c7d3fac27f1150ac29b1d8b2076c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 17, 2026.

Transparency log

Security for webshocket 0.5.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for webshocket-0.5.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page