import sys import asyncio async def handle_incoming_connection(reader, writer): connection_extra_info = writer.get_extra_info('peername') read_bytes = await reader.read(100) if len(read_bytes) == 0: print(connection_extra_info) return print("Received %r from %r" % (read_bytes, connection_extra_info)) print("Send: %r" % read_bytes) writer.write(read_bytes) await writer.drain() print("Close the client socket") writer.close() if sys.platform == 'win32': loop = asyncio.ProactorEventLoop() else: loop = asyncio.get_event_loop() asyncio.set_event_loop(loop) server_listen_coroutine = asyncio.start_server(handle_incoming_connection, '127.0.0.1', 8888, loop=loop) server = loop.run_until_complete(server_listen_coroutine) # This locks up until there are network events, so Ctrl+C won't take effect until try: loop.run_forever() except KeyboardInterrupt: print("Main loop interrupted by CTRL-C") server.close() loop.run_until_complete(server.wait_closed()) print("Cleaning up loop.", loop) loop.close() print("Loop exited.")