async_wget.py 758 B

12345678910111213141516171819202122232425
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import asyncio
  4. @asyncio.coroutine
  5. def wget(host):
  6. print('wget %s...' % host)
  7. connect = asyncio.open_connection(host, 80)
  8. reader, writer = yield from connect
  9. header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
  10. writer.write(header.encode('utf-8'))
  11. yield from writer.drain()
  12. while True:
  13. line = yield from reader.readline()
  14. if line == b'\r\n':
  15. break
  16. print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
  17. # Ignore the body, close the socket
  18. writer.close()
  19. loop = asyncio.get_event_loop()
  20. tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
  21. loop.run_until_complete(asyncio.wait(tasks))
  22. loop.close()