Python/asynchatPing.py
author morrowa
Thu Jul 02 17:51:35 2009 -0700 (2009-07-02)
changeset 55 f240f9023393
permissions -rw-r--r--
Made C99 project default.
     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()