morrowa@51: # asynchatPing morrowa@51: # Uses asynchat morrowa@51: # Not related to BLIP - just to aid in my understanding of what's going on morrowa@51: # Sends "Ping", waits for "Pong" morrowa@51: morrowa@51: import socket morrowa@51: import asyncore morrowa@51: import asynchat morrowa@51: morrowa@51: kNumPings = 10 morrowa@51: morrowa@51: class asynchatPing(asynchat.async_chat): morrowa@51: def __init__(self, address): morrowa@51: asynchat.async_chat.__init__(self) morrowa@51: self.create_socket(socket.AF_INET, socket.SOCK_STREAM) morrowa@51: self.connect(address) morrowa@51: self.set_terminator("Pong") morrowa@51: self.pingsSent = self.pongsGot = 0 morrowa@51: self.donePing = self.donePong = False morrowa@51: morrowa@51: def handle_connect(self): morrowa@51: print "Connected" morrowa@51: morrowa@51: def handle_close(self): morrowa@51: print "Closed" morrowa@51: asynchat.async_chat.handle_close(self) morrowa@51: morrowa@51: def collect_incoming_data(self, data): morrowa@51: """discard data""" morrowa@51: pass morrowa@51: morrowa@51: def found_terminator(self): morrowa@51: """when we get a Pong""" morrowa@51: print "Received 'Pong'" morrowa@51: self.pongsGot += 1 morrowa@51: if self.pongsGot == kNumPings: morrowa@51: print "Done ponging" morrowa@51: self.donePong = True morrowa@51: self.close_when_done() morrowa@51: morrowa@51: def ping(self): morrowa@51: if not self.donePing: morrowa@51: self.push("Ping") morrowa@51: print "Sent 'Ping'" morrowa@51: self.pingsSent += 1 morrowa@51: if self.pingsSent == kNumPings: morrowa@51: print "Done pinging" morrowa@51: self.donePing = True morrowa@51: morrowa@51: def run(self): morrowa@51: timeout = 0 morrowa@51: while not self.donePing: morrowa@51: self.ping() morrowa@51: asyncore.loop(timeout=timeout, count=1) morrowa@51: asyncore.loop() morrowa@51: print "Done!" morrowa@51: morrowa@51: if __name__ == '__main__': morrowa@51: ping = asynchatPing( ('localhost', 1337) ) morrowa@51: ping.run()