asyncio3.py 1001 B

1234567891011121314151617181920212223242526272829303132333435
  1. """
  2. 异步I/O操作 - asyncio模块
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-21
  6. """
  7. import asyncio
  8. async def wget(host):
  9. print('wget %s...' % host)
  10. connect = asyncio.open_connection(host, 80)
  11. # 异步方式等待连接结果
  12. reader, writer = await connect
  13. header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
  14. writer.write(header.encode('utf-8'))
  15. # 异步I/O方式执行写操作
  16. await writer.drain()
  17. while True:
  18. # 异步I/O方式执行读操作
  19. line = await reader.readline()
  20. if line == b'\r\n':
  21. break
  22. print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
  23. writer.close()
  24. loop = asyncio.get_event_loop()
  25. # 通过生成式语法创建一个装了三个协程的列表
  26. hosts_list = ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']
  27. tasks = [wget(host) for host in hosts_list]
  28. # 下面的方法将异步I/O操作放入EventLoop直到执行完毕
  29. loop.run_until_complete(asyncio.wait(tasks))
  30. loop.close()