Skip to main content

A lightweight async TCP server framework built on asyncio

Project description

aiosocket

A lightweight async TCP server framework built on Python's asyncio. Provides a decorator-based API for defining handlers, middleware, and filter-based routing — similar in spirit to Flask, but for raw TCP connections.

Requirements

Python 3.10+

Installation

pip install aiosocket-python

Quick Start

import asyncio
import aiosocket

server = aiosocket.AsyncTCPServer(host="127.0.0.1", port=8888)

@server.callback()
async def echo(reader: aiosocket.Reader, writer: aiosocket.Writer):
    data = await reader.data()
    await writer.send(data)

async def main():
    await server.start()
    await asyncio.Event().wait()  # run forever

asyncio.run(main())

Filters

Use Filter to route connections based on raw data patterns or JSON fields.

from aiosocket import AsyncTCPServer, Filter

server = AsyncTCPServer("127.0.0.1", 8888)

# Match raw bytes with a regex pattern
text_filter = Filter(pattern=r"^HELLO.*")

# Match JSON fields
login_filter = Filter(action="login")

@server.callback(login_filter)
async def handle_login(reader, writer):
    payload = await reader.json()
    await writer.send({"status": "ok", "user": payload["user"]})

@server.callback(text_filter)
async def handle_hello(reader, writer):
    await writer.send(b"Hello to you too!\n")

Middleware

Middleware runs before callbacks and can populate a shared data dict passed as **kwargs to the matched callback.

@server.middleware()
async def log_request(reader, writer, data):
    raw = await reader.data()
    print(f"Received {len(raw)} bytes")

@server.middleware(login_filter)
async def authenticate(reader, writer, data):
    payload = await reader.json()
    data["user"] = payload.get("user")

@server.callback(login_filter)
async def greet(reader, writer, user=None):
    await writer.send(f"Welcome, {user}!".encode())

Routers

Split your handlers across modules using Router, then mount them on the server.

from aiosocket import Router

router = Router()

@router.callback()
async def handle(reader, writer):
    await writer.send(b"OK\n")

# in your main file:
server.include_router(router)

API Reference

AsyncTCPServer(host, port)

  • .callback(*filters) — decorator that registers a connection handler
  • .middleware(*filters) — decorator that registers middleware
  • .include_router(router) — merge a Router's handlers into this server
  • .start() — start listening (coroutine)
  • .stop() — gracefully shut down (coroutine)

Reader

  • .data() -> bytes — read up to 64 KiB; result is cached
  • .json() -> dict — parse data as JSON; result is cached

Writer

  • .send(data: bytes | str | dict) — write and drain; dicts are JSON-serialized
  • .close() — close the connection

Filter(pattern=None, **json_fields)

  • pattern — regex matched against the raw decoded bytes
  • **json_fields — key/value pairs matched against the parsed JSON body

Router

  • .callback(*filters) — same as AsyncTCPServer.callback
  • .middleware(*filters) — same as AsyncTCPServer.middleware

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiosocket_python-0.1.0.tar.gz (7.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiosocket_python-0.1.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file aiosocket_python-0.1.0.tar.gz.

File metadata

  • Download URL: aiosocket_python-0.1.0.tar.gz
  • Upload date:
  • Size: 7.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for aiosocket_python-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ec7184a0998e36008d900007c9ae9b5904f414e3b38a19c9adb8a852ea286621
MD5 0dacefb172065311f1b6edbf6b3a9124
BLAKE2b-256 aeb6687be46842d46426baa47bcf1538d49ccfd82e39730a1cc53bce896c1fff

See more details on using hashes here.

File details

Details for the file aiosocket_python-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aiosocket_python-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a0d43e2e8615c07d650565092b20d3571ca422e4a5f738ef20784f89bc583e01
MD5 f80b326ad835be3135021f697ca4f90f
BLAKE2b-256 9ac2aef1bb9f6c34966f29d1eb53879a5c56615ea2f83e18e5f528cb44fa1280

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page