morrowa@51: # asynchatPong morrowa@51: # Listener using asynchat morrowa@51: # Not related to BLIP - just to aid in my understanding of what's going on morrowa@51: # Sends "Pong" when it gets "Ping" morrowa@51: morrowa@51: import sys morrowa@51: import traceback morrowa@51: import socket morrowa@51: import asyncore morrowa@51: import asynchat morrowa@51: morrowa@51: class asynchatPongListener(asyncore.dispatcher): morrowa@51: def __init__(self, port): morrowa@51: asyncore.dispatcher.__init__(self) morrowa@51: self.create_socket(socket.AF_INET, socket.SOCK_STREAM) morrowa@51: self.bind( ('', port) ) morrowa@51: self.listen(2) morrowa@51: self.shouldAccept = True morrowa@51: morrowa@51: def handle_accept(self): morrowa@51: if self.shouldAccept: morrowa@51: sock, addr = self.accept() morrowa@51: self.conn = asynchatPong(sock, self) morrowa@51: self.shouldAccept = False morrowa@51: morrowa@51: def handle_error(self): morrowa@51: (typ,val,trace) = sys.exc_info() morrowa@51: print "Listener caught: %s %s\n%s" % (typ,val,traceback.format_exc()) morrowa@51: self.close() morrowa@51: morrowa@51: def handle_close(self): morrowa@51: print "Listener got close" morrowa@51: asyncore.dispatcher.handle_close(self) morrowa@51: morrowa@51: class asynchatPong(asynchat.async_chat): morrowa@51: def __init__(self, socket, listener): morrowa@51: asynchat.async_chat.__init__(self, socket) morrowa@51: self._listener = listener morrowa@51: self.set_terminator("Ping") morrowa@51: morrowa@51: def collect_incoming_data(self, data): morrowa@51: """called when arbitrary amount of data arrives. we just eat it""" morrowa@51: pass morrowa@51: morrowa@51: def found_terminator(self): morrowa@51: """called when the terminator we set is found""" morrowa@51: print "Found 'Ping'" morrowa@51: self.push("Pong") morrowa@51: print "Sent 'Pong'" morrowa@51: morrowa@51: def handle_close(self): morrowa@51: print "Closed; closing listener" morrowa@51: self._listener.close() morrowa@51: asynchat.async_chat.handle_close(self) morrowa@51: morrowa@51: morrowa@51: if __name__ == '__main__': morrowa@51: pong = asynchatPongListener(1337) morrowa@51: asyncore.loop()