connect.py 759 B

12345678910111213141516171819202122232425262728
  1. """Spawn multiple workers and collect their results.
  2. Demonstrates how to use the eventlet.green.socket module.
  3. """
  4. from __future__ import print_function
  5. import eventlet
  6. from eventlet.green import socket
  7. def geturl(url):
  8. c = socket.socket()
  9. ip = socket.gethostbyname(url)
  10. c.connect((ip, 80))
  11. print('%s connected' % url)
  12. c.sendall('GET /\r\n\r\n')
  13. return c.recv(1024)
  14. urls = ['www.google.com', 'www.yandex.ru', 'www.python.org']
  15. pile = eventlet.GreenPile()
  16. for x in urls:
  17. pile.spawn(geturl, x)
  18. # note that the pile acts as a collection of return values from the functions
  19. # if any exceptions are raised by the function they'll get raised here
  20. for url, result in zip(urls, pile):
  21. print('%s: %s' % (url, repr(result)[:50]))