asyncio-dgram

3.0.0 · active · verified Fri Apr 17

asyncio-dgram provides a higher-level, more convenient API for working with UDP datagram sockets in Python's asyncio framework. It simplifies common UDP operations like binding, connecting, sending, and receiving data with an async/await interface. The current version is 3.0.0, and it generally follows a release cadence driven by feature additions, bug fixes, and API improvements.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates a simple UDP server and client using `asyncio-dgram`. The server binds to a port, receives a message, and echoes it back. The client connects to the server, sends a message, and receives the echo. Both use the `async with` syntax for managing the datagram stream.

import asyncio
from asyncio_dgram import bind, connect

async def udp_server(host, port):
    async with bind((host, port)) as stream:
        print(f"Server: Listening on {host}:{port}")
        data, remote_addr = await stream.recv()
        message = data.decode()
        print(f"Server: Received '{message}' from {remote_addr}")
        response = f"Hello from server! You sent: '{message}'".encode()
        await stream.send(response, remote_addr)
        print(f"Server: Sent '{response.decode()}' back to {remote_addr}")
    print("Server: Stream closed.")

async def udp_client(host, port, message):
    async with connect((host, port)) as stream:
        print(f"Client: Sending '{message}' to {host}:{port}")
        await stream.send(message.encode())
        data, remote_addr = await stream.recv()
        response = data.decode()
        print(f"Client: Received '{response}' from {remote_addr}")
    print("Client: Stream closed.")

async def main():
    host = '127.0.0.1'
    port = 9999

    server_task = asyncio.create_task(udp_server(host, port))
    # Give the server a moment to start listening
    await asyncio.sleep(0.1)
    client_task = asyncio.create_task(udp_client(host, port, "Hello UDP World!"))

    await asyncio.gather(server_task, client_task)

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →