Python/asynchatPong.py
author morrowa
Tue Jun 23 12:46:40 2009 -0700 (2009-06-23)
changeset 53 e9f209a24d53
permissions -rw-r--r--
Connections opened by listeners now close correctly.
     1 # asynchatPong
     2 # Listener using asynchat
     3 # Not related to BLIP - just to aid in my understanding of what's going on
     4 # Sends "Pong" when it gets "Ping"
     5 
     6 import sys
     7 import traceback
     8 import socket
     9 import asyncore
    10 import asynchat
    11 
    12 class asynchatPongListener(asyncore.dispatcher):
    13     def __init__(self, port):
    14         asyncore.dispatcher.__init__(self)
    15         self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    16         self.bind( ('', port) )
    17         self.listen(2)
    18         self.shouldAccept = True
    19     
    20     def handle_accept(self):
    21         if self.shouldAccept:
    22             sock, addr = self.accept()
    23             self.conn = asynchatPong(sock, self)
    24             self.shouldAccept = False
    25     
    26     def handle_error(self):
    27         (typ,val,trace) = sys.exc_info()
    28         print "Listener caught: %s %s\n%s" % (typ,val,traceback.format_exc())
    29         self.close()
    30     
    31     def handle_close(self):
    32         print "Listener got close"
    33         asyncore.dispatcher.handle_close(self)
    34 
    35 class asynchatPong(asynchat.async_chat):
    36     def __init__(self, socket, listener):
    37         asynchat.async_chat.__init__(self, socket)
    38         self._listener = listener
    39         self.set_terminator("Ping")
    40     
    41     def collect_incoming_data(self, data):
    42         """called when arbitrary amount of data arrives. we just eat it"""
    43         pass
    44     
    45     def found_terminator(self):
    46         """called when the terminator we set is found"""
    47         print "Found 'Ping'"
    48         self.push("Pong")
    49         print "Sent 'Pong'"
    50     
    51     def handle_close(self):
    52         print "Closed; closing listener"
    53         self._listener.close()
    54         asynchat.async_chat.handle_close(self)
    55     
    56 
    57 if __name__ == '__main__':
    58     pong = asynchatPongListener(1337)
    59     asyncore.loop()