Commit 3dd59ede authored by Alan Marchiori's avatar Alan Marchiori

fixed async

parent 4974c0ba
Asyncio udp echo/caps server
Alan Marchiori 2019
May be different in python >3.6, requires python >3.5
import logging
import asyncio # note not socket or socketserver!
import time
class MyUdpProtocol:
def __init__(self, server_address, log, loop):
# pass in a logger instance, just for demo,
# in production we could create a logger
self.log = log
self.loop = loop
self.server_address = server_address # just for printing
def connection_made(self, transport):
self.transport = transport"connection_made: {}".format(
def connection_lost(self):
"this is never called for udp since it is connecitonless""connection_lost")
async def handle_response(self, data, addr):
"simulate a long running response method"
# processing delay
await asyncio.sleep(3)
# interpret as utf-8 string, uppercase, then convert (encode)
# as raw bytes for the network
newdata = data.decode("utf-8").upper().encode()
self.transport.sendto(newdata, addr)"{} <- {}: {}".format(
addr, self.server_address, newdata))
def datagram_received(self, data, addr):
datagram_received cannot be a coroutine but it can schedule
a long running task to handle the request.
# log rx."{} -> {}: {}".format(
addr, self.server_address, data))
self.loop.create_task(self.handle_response(data, addr))
if __name__ == "__main__":
FORMAT = '%(asctime)-15s %(levelname)-6s [%(threadName)-10s]: %(message)s'
server_address = ('', 8888)
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
log = logging.getLogger()
# get the event loop in the current thread
loop = asyncio.get_event_loop()
# create_datagram_endpoint returns a coroutine
server_task = loop.create_datagram_endpoint(
lambda: MyUdpProtocol(server_address, log, loop),
local_addr = server_address
# a coroutine can be scheduled
# run the event loop forever
except KeyboardInterrupt:"Ctrl-c quit!")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment