|
- #!/usr/bin/env python3
- # -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil -*-
- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
-
- import sys
- import asyncio
-
-
- class EchoServerProtocol:
- 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))
- self.transport.sendto(data, addr)
-
- #def datagram_received(self, data, addr):
- # loop = asyncio.get_event_loop()
- # loop.create_task(self.handle_income_packet(data, addr))
-
- #async def handle_income_packet(self, data, addr):
- # # echo back the message, but 2 seconds later
- # await asyncio.sleep(2)
- # self.transport.sendto(data, addr)
-
-
- async def server_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()
-
- # 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()
-
-
- 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):
- self.transport = transport
- print('Send:', self.message)
- self.transport.sendto(self.message.encode())
-
- def datagram_received(self, data, addr):
- print("Received:", data.decode())
-
- 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 client_main():
- # Get a reference to the event loop as we plan to use
- # low-level APIs.
- loop = asyncio.get_running_loop()
-
- 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()
-
-
- if __name__ == '__main__':
- if sys.argv[1] == '-s':
- asyncio.run(server_main())
- else:
- asyncio.run(client_main())
|