Python/asynchatPing.py
author morrowa@betelgeuse.local
Tue Jun 23 11:44:30 2009 -0700 (2009-06-23)
changeset 51 de59ce19f42e
permissions -rw-r--r--
BROKEN COMMIT. Majority of code to handle closing has been added. Listeners do not close correctly.
     1 # asynchatPing
     2 # Uses asynchat
     3 # Not related to BLIP - just to aid in my understanding of what's going on
     4 # Sends "Ping", waits for "Pong"
     5 
     6 import socket
     7 import asyncore
     8 import asynchat
     9 
    10 kNumPings = 10
    11 
    12 class asynchatPing(asynchat.async_chat):
    13     def __init__(self, address):
    14         asynchat.async_chat.__init__(self)
    15         self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    16         self.connect(address)
    17         self.set_terminator("Pong")
    18         self.pingsSent = self.pongsGot = 0
    19         self.donePing = self.donePong = False
    20     
    21     def handle_connect(self):
    22         print "Connected"
    23     
    24     def handle_close(self):
    25         print "Closed"
    26         asynchat.async_chat.handle_close(self)
    27     
    28     def collect_incoming_data(self, data):
    29         """discard data"""
    30         pass
    31     
    32     def found_terminator(self):
    33         """when we get a Pong"""
    34         print "Received 'Pong'"
    35         self.pongsGot += 1
    36         if self.pongsGot == kNumPings:
    37             print "Done ponging"
    38             self.donePong = True
    39             self.close_when_done()
    40     
    41     def ping(self):
    42         if not self.donePing:
    43             self.push("Ping")
    44             print "Sent 'Ping'"
    45             self.pingsSent += 1
    46             if self.pingsSent == kNumPings:
    47                 print "Done pinging"
    48                 self.donePing = True
    49     
    50     def run(self):
    51         timeout = 0
    52         while not self.donePing:
    53             self.ping()
    54             asyncore.loop(timeout=timeout, count=1)
    55         asyncore.loop()
    56         print "Done!"
    57 
    58 if __name__ == '__main__':
    59     ping = asynchatPing( ('localhost', 1337) )
    60     ping.run()