IoHandler.py 1.44 KB
"""
@author Georg Hopp

"""
from contextlib import contextmanager

import Transport

from Event.EventHandler import EventHandler
from Communication.EndPoint import CommunicationEndPoint

class IoHandler(EventHandler):
    def __init__(self):
        super(IoHandler, self).__init__()

        self._event_methods = {
            CommunicationEndPoint.eventId('read_ready')  : self._read,
            CommunicationEndPoint.eventId('write_ready') : self._write
        }

    @contextmanager
    def _doio(self, subject, shutdown_type):
        try:
            yield
        except Transport.Error as error:
            if Transport.Error.ERR_REMOTE_CLOSE == error.errno:
                self.issueEvent(subject, shutdown_type)
            else:
                self.issueEvent(subject, 'close')

    def _read(self, event):
        with self._doio(event.subject, 'shutdown_read'):
            if event.subject.bufferRead():
                self.issueEvent(event.subject, 'new_data')

    def _write(self, event):
        with self._doio(event.subject, 'shutdown_write'):
            if event.subject.writeBuffered():
                if event.subject.hasPendingData():
                    self.issueEvent(event.subject, 'pending_data')
                else:
                    self.issueEvent(event.subject, 'end_data')
                    if event.subject.shouldClose():
                        self.issueEvent(event.subject, 'close')

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