import asynchat
class Protocol(asynchat.async_chat):
    def __init__(self, connection, multiplexer):
        asynchat.async_chat.__init__(self, connection)
        # we are doing input buffering
        self.buffer = ""
        # we have a newline-terminated protocol
        self.set_terminator("\n")
        
        (peerhost, peerport) = connection.getpeername()
        # some kind of identification
        self.source = peerhost + ":" + peerport.__str__()
        
        self.multiplexer = multiplexer
        self.multiplexer.connect(self)

    def handle_close(self):
        # called if the socket gets closed
        multiplexer.disconnect(self)
        self.close()
    def collect_incoming_data(self, data):
        # called whenever data arrives on the socket
        self.buffer = self.buffer + data
    def getsource(self):
        # little helper
        return self.source
    def found_terminator(self):
        # this will do the protocol parsing
        line = self.buffer
        self.buffer = ""
        self.multiplexer.castmsg(line)
    def render(self, data):
        # this will do output formatting soon
        # but now it simply pushes data over the socket as is
        self.push(data + "\n")

