EndPoint.py 2.39 KB
"""
Associate a physical transport layer with a protocol.

Author: Georg Hopp <ghopp@spamtitan.com>
"""
import errno

from Event.EventSubject import EventSubject

class CommunicationEndPoint(EventSubject):
    _EVENTS = {
        'read_ready'     : 0x01,
        'write_ready'    : 0x02,
        'upgrade'        : 0x03,
        'new_data'       : 0x04,
        'pending_data'   : 0x05,
        'end_data'       : 0x06,
        'new_msg'        : 0x07,
        'send_msg'       : 0x08,
        'shutdown_read'  : 0x09,
        'shutdown_write' : 0x10,
        'close'          : 0x11
    }

    def __init__(self, transport, protocol, read_chunk_size=8192):
        super(CommunicationEndPoint, self).__init__()
        self.setProtocol(protocol)
        self._transport       = transport
        self._read_chunk_size = read_chunk_size
        self._do_close        = False

    def setClose(self):
        self._do_close = True

    def hasProtocol(self, protocol):
        return isinstance(self.getProtocol(), protocol)

    def hasPendingData(self):
        return False

    def shouldClose(self):
        return self._do_close

    def getTransport(self):
        return self._transport

    def setProtocol(self, protocol):
        self._protocol = protocol

    def getProtocol(self):
        return self._protocol

    def getHandle(self):
        return self.getTransport().getHandle()

    def appendReadData(self, data_remote):
        pass

    def nextWriteData(self):
        return None

    def appendWriteData(self, data_remote):
        pass

    def bufferRead(self):
        data_remote = self._transport.recv(self._read_chunk_size)

        if not data_remote:
            return False

        while data_remote:
            self.appendReadData(data_remote)
            data_remote = self._transport.recv(self._read_chunk_size)

        return True

    def writeBuffered(self):
        data, remote = self.nextWriteData()
        send         = 0

        while data:
            current_send = self._transport.send(data, remote)
            if 0 == current_send:
                if data:
                    self.appendWriteData((data, remote))
                break

            send += current_send
            data = data[send:]
            if not data:
                data, remote = self.nextWriteData()

        if 0 == send:
            return False

        return True

# vim: set ft=python et ts=8 sw=4 sts=4: