Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Asyncore example

By: a guest on Dec 13th, 2011  |  syntax: Python  |  size: 0.94 KB  |  views: 82  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #! /usr/bin/env python
  2.  
  3. import asyncore, socket, sys
  4.  
  5. class http_client(asyncore.dispatcher):
  6.  
  7.     def __init__(self, host, path):
  8.         asyncore.dispatcher.__init__(self)
  9.         self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  10.         self.connect( (host, 80) )
  11.         self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path
  12.  
  13.     def handle_connect(self):
  14.         pass
  15.  
  16.     def handle_close(self):
  17.         self.close()
  18.  
  19.     def handle_read(self):
  20.         a = self.recv(8192)
  21.         if len(a):
  22.                         print len(a), ' ',
  23.                         sys.stdout.flush()
  24.  
  25.     def writable(self):
  26.         return (len(self.buffer) > 0)
  27.  
  28.     def handle_write(self):
  29.         sent = self.send(self.buffer)
  30.         self.buffer = self.buffer[sent:]
  31.  
  32. a = dict((cl, cl) for cl in [http_client('www.python.org', '/') for _ in xrange(10)])
  33.  
  34. #asyncore.loop(timeout=0.1, use_poll=True, map=a) # always hangs up
  35. #asyncore.loop(timeout=0.1, use_poll=True)        # works fine
  36.  
  37.