diff --git a/examples/async_wget.py b/examples/async_wget.py new file mode 100644 index 0000000..57bc68e --- /dev/null +++ b/examples/async_wget.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 + +import asyncio + +async def wget(host): + print("wget %s ...", host) + connect = asyncio.open_connection(host, 80) + reader, writer = await connect + + header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host + writer.write(header.encode()) + await writer.drain() + + while True: + line = await reader.readline() + if line == b'\r\n': + break + print("%s header > %s" % (host, line.decode().rstrip())) + + writer.close() + + +loop = asyncio.get_event_loop() +tasks = [wget(host) for host in ["www.sina.com", "www.sohu.com", "www.163.com"]] +loop.run_until_complete(asyncio.wait(tasks)) +loop.close() + + \ No newline at end of file diff --git a/examples/echo/async_tcp_client.py b/examples/echo/async_tcp_client.py new file mode 100644 index 0000000..bbc9ea9 --- /dev/null +++ b/examples/echo/async_tcp_client.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 + +import asyncio + +async def echo_tcp_client(message, loop): + reader, writer = await asyncio.open_connection('127.0.0.1', 8888, loop=loop) + + print("发送数据: %r" % message) + writer.write(message.encode()) + + data = await reader.read(100) + print("接收数据: %r" % data.decode()) + + print("关闭socket连接") + writer.close() + +message = "Hello World!" +loop = asyncio.get_event_loop() +loop.run_until_complete(echo_tcp_client(message, loop)) +loop.close() diff --git a/examples/echo/async_tcp_server.py b/examples/echo/async_tcp_server.py new file mode 100644 index 0000000..ad643f5 --- /dev/null +++ b/examples/echo/async_tcp_server.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +import asyncio + +async def handle_echo(reader, writer): + + data = await reader.read(100) + + message = data.decode() + addr = writer.get_extra_info('peername') + print("> 接收到数据 %r From %r" % (message, addr)) + + print("> 发送数据: %r" % message) + writer.write(data) + await writer.drain() + writer.close() + +loop = asyncio.get_event_loop() +coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop) +server = loop.run_until_complete(coro) +print('Serving on {}'.format(server.sockets[0].getsockname())) +try: + loop.run_forever() +except KeyboardInterrupt: + pass + + +server.close() +loop.run_until_complete(server.wait_closed()) +loop.close() \ No newline at end of file