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