Python 3.4+Async programmingterm
asyncio.DatagramProtocol
protocols and transports
The protocol for datagrams (UDP): the loop calls datagram_received(data, addr) for every packet and error_received() on a send or receive error.
Syntax
transport, protocol = await loop.create_datagram_endpoint(ProtocolClass, local_addr=...)
asyncio has no high-level streams API for UDP, so DatagramProtocol is the only built-in route. Unlike TCP, message boundaries survive: one sendto() means one datagram_received(), but delivery and order are not guaranteed. Send with transport.sendto(), not write(); error_received() often signals an ICMP 'port unreachable' after sendto() to a closed port.
Examples
import asyncio
class Collector(asyncio.DatagramProtocol):
def datagram_received(self, data, addr):
print('пакет', data) # → пакет b'one' / пакет b'two'
async def main():
loop = asyncio.get_running_loop()
server, _ = await loop.create_datagram_endpoint(Collector, local_addr=('127.0.0.1', 0))
addr = server.get_extra_info('sockname')
client, _ = await loop.create_datagram_endpoint(
asyncio.DatagramProtocol, remote_addr=addr)
client.sendto(b'one')
client.sendto(b'two')
await asyncio.sleep(0.01)
client.close()
server.close()
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy