Asyncio high level UDP sockets

Asyncio high level UDP sockets.

Project homepage: https://github.com/eerimoq/asyncudp

Documentation: https://asyncudp.readthedocs.org/en/latest

Installation

$ pip install asyncudp

Example client

import asyncio
import asyncudp

async def main():
    sock = await asyncudp.create_socket(remote_addr=('127.0.0.1', 9999))
    sock.sendto(b'Hello!')
    print(await sock.recvfrom())
    sock.close()

asyncio.run(main())

Example server

import asyncio
import asyncudp

async def main():
    sock = await asyncudp.create_socket(local_addr=('127.0.0.1', 9999))

    while True:
        data, addr = await sock.recvfrom()
        print(data, addr)
        sock.sendto(data, addr)

asyncio.run(main())

Test

$ python3 -m unittest

Examples

Client

import asyncio
import asyncudp

async def main():
    sock = await asyncudp.create_socket(remote_addr=('127.0.0.1', 9999))
    sock.sendto(b'Hello!')
    print(await sock.recvfrom())
    sock.close()

asyncio.run(main())

Server

import asyncio
import asyncudp

async def main():
    sock = await asyncudp.create_socket(local_addr=('127.0.0.1', 9999))

    while True:
        data, addr = await sock.recvfrom()
        print(data, addr)
        sock.sendto(data, addr)

asyncio.run(main())

Functions and classes

async asyncudp.create_socket(local_addr=None, remote_addr=None, packets_queue_max_size=0, reuse_port=None)[source]

Create a UDP socket with given local and remote addresses.

>>> sock = await asyncudp.create_socket(local_addr=('127.0.0.1', 9999))
class asyncudp.Socket(transport, protocol)[source]

A UDP socket. Use create_socket() to create an instance of this class.

close()[source]

Close the socket.

sendto(data, addr=None)[source]

Send given packet to given address addr. Sends to remote_addr given to the constructor if addr is None.

Raises an error if a connection error has occurred.

>>> sock.sendto(b'Hi!')
async recvfrom()[source]

Receive a UDP packet.

Raises ClosedError on connection error, often by calling the close() method from another task. May raise other errors as well.

>>> data, addr = sock.recvfrom()
getsockname()[source]

Get bound infomation.

>>> local_address, local_port = sock.getsockname()