### Put the below into a separate server.py file import asyncio class EchoServerProtocol(asyncio.DatagramProtocol): def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): message = data.decode() print('Received %r from %s' % (message, addr)) print('Send %r to %s' % (message, addr)) print('Server transport closing due to client abort?', self.transport.is_closing()) self.transport.sendto(data, addr) def error_received(self, exc): print("Exception thrown caught by 'error_received': %s" % exc) async def main(): print("Starting UDP server") # Get a reference to the event loop as we plan to use # low-level APIs. loop = asyncio.get_running_loop() # Has no effect on the occurrence of this issue loop.set_debug(True) # One protocol instance will be created to serve all # client requests. transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(), local_addr=('127.0.0.1', 9999)) try: await asyncio.sleep(3600) # Serve for 1 hour. finally: transport.close() asyncio.run(main()) ### Put the below into a separate client.py file import asyncio class EchoClientProtocol: def __init__(self, message, on_con_lost): self.message = message self.on_con_lost = on_con_lost self.transport = None def connection_made(self, transport: asyncio.DatagramTransport): self.transport = transport print('Send:', self.message) self.transport.sendto(self.message.encode()) # Try to force the server to raise the error # 'No services is operation at the destination network endpoint on the remote system' self.transport.abort() def datagram_received(self, data, addr): print("Received:", data) print("Close the socket") self.transport.close() def error_received(self, exc): print('Error received:', exc) def connection_lost(self, exc): print("Connection closed") self.on_con_lost.set_result(True) async def main(): # Get a reference to the event loop as we plan to use # low-level APIs. loop = asyncio.get_running_loop() # Uncomment me to see the error disappear!! # loop.set_debug(True) on_con_lost = loop.create_future() message = "Hello World!" transport, protocol = await loop.create_datagram_endpoint( lambda: EchoClientProtocol(message, on_con_lost), remote_addr=('127.0.0.1', 9999)) try: await on_con_lost finally: transport.close() asyncio.run(main())