1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/Python/asynchatPong.py Tue Jun 23 12:46:40 2009 -0700
1.3 @@ -0,0 +1,59 @@
1.4 +# asynchatPong
1.5 +# Listener using asynchat
1.6 +# Not related to BLIP - just to aid in my understanding of what's going on
1.7 +# Sends "Pong" when it gets "Ping"
1.8 +
1.9 +import sys
1.10 +import traceback
1.11 +import socket
1.12 +import asyncore
1.13 +import asynchat
1.14 +
1.15 +class asynchatPongListener(asyncore.dispatcher):
1.16 + def __init__(self, port):
1.17 + asyncore.dispatcher.__init__(self)
1.18 + self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
1.19 + self.bind( ('', port) )
1.20 + self.listen(2)
1.21 + self.shouldAccept = True
1.22 +
1.23 + def handle_accept(self):
1.24 + if self.shouldAccept:
1.25 + sock, addr = self.accept()
1.26 + self.conn = asynchatPong(sock, self)
1.27 + self.shouldAccept = False
1.28 +
1.29 + def handle_error(self):
1.30 + (typ,val,trace) = sys.exc_info()
1.31 + print "Listener caught: %s %s\n%s" % (typ,val,traceback.format_exc())
1.32 + self.close()
1.33 +
1.34 + def handle_close(self):
1.35 + print "Listener got close"
1.36 + asyncore.dispatcher.handle_close(self)
1.37 +
1.38 +class asynchatPong(asynchat.async_chat):
1.39 + def __init__(self, socket, listener):
1.40 + asynchat.async_chat.__init__(self, socket)
1.41 + self._listener = listener
1.42 + self.set_terminator("Ping")
1.43 +
1.44 + def collect_incoming_data(self, data):
1.45 + """called when arbitrary amount of data arrives. we just eat it"""
1.46 + pass
1.47 +
1.48 + def found_terminator(self):
1.49 + """called when the terminator we set is found"""
1.50 + print "Found 'Ping'"
1.51 + self.push("Pong")
1.52 + print "Sent 'Pong'"
1.53 +
1.54 + def handle_close(self):
1.55 + print "Closed; closing listener"
1.56 + self._listener.close()
1.57 + asynchat.async_chat.handle_close(self)
1.58 +
1.59 +
1.60 +if __name__ == '__main__':
1.61 + pong = asynchatPongListener(1337)
1.62 + asyncore.loop()