Python/asynchatPing.py
changeset 53 e9f209a24d53
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/Python/asynchatPing.py	Tue Jun 23 12:46:40 2009 -0700
     1.3 @@ -0,0 +1,60 @@
     1.4 +# asynchatPing
     1.5 +# Uses asynchat
     1.6 +# Not related to BLIP - just to aid in my understanding of what's going on
     1.7 +# Sends "Ping", waits for "Pong"
     1.8 +
     1.9 +import socket
    1.10 +import asyncore
    1.11 +import asynchat
    1.12 +
    1.13 +kNumPings = 10
    1.14 +
    1.15 +class asynchatPing(asynchat.async_chat):
    1.16 +    def __init__(self, address):
    1.17 +        asynchat.async_chat.__init__(self)
    1.18 +        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    1.19 +        self.connect(address)
    1.20 +        self.set_terminator("Pong")
    1.21 +        self.pingsSent = self.pongsGot = 0
    1.22 +        self.donePing = self.donePong = False
    1.23 +    
    1.24 +    def handle_connect(self):
    1.25 +        print "Connected"
    1.26 +    
    1.27 +    def handle_close(self):
    1.28 +        print "Closed"
    1.29 +        asynchat.async_chat.handle_close(self)
    1.30 +    
    1.31 +    def collect_incoming_data(self, data):
    1.32 +        """discard data"""
    1.33 +        pass
    1.34 +    
    1.35 +    def found_terminator(self):
    1.36 +        """when we get a Pong"""
    1.37 +        print "Received 'Pong'"
    1.38 +        self.pongsGot += 1
    1.39 +        if self.pongsGot == kNumPings:
    1.40 +            print "Done ponging"
    1.41 +            self.donePong = True
    1.42 +            self.close_when_done()
    1.43 +    
    1.44 +    def ping(self):
    1.45 +        if not self.donePing:
    1.46 +            self.push("Ping")
    1.47 +            print "Sent 'Ping'"
    1.48 +            self.pingsSent += 1
    1.49 +            if self.pingsSent == kNumPings:
    1.50 +                print "Done pinging"
    1.51 +                self.donePing = True
    1.52 +    
    1.53 +    def run(self):
    1.54 +        timeout = 0
    1.55 +        while not self.donePing:
    1.56 +            self.ping()
    1.57 +            asyncore.loop(timeout=timeout, count=1)
    1.58 +        asyncore.loop()
    1.59 +        print "Done!"
    1.60 +
    1.61 +if __name__ == '__main__':
    1.62 +    ping = asynchatPing( ('localhost', 1337) )
    1.63 +    ping.run()