SimpleClient.py 2.55 KB
import time

from Event.EventDispatcher import EventDispatcher, CLIENT
from Event.EventHandler import EventHandler
import Event.Signal as Signal

from Communication.Manager import CommunicationManager
from Communication.EndPoint import CommunicationEndPoint
from Communication.ProtocolHandler import ProtocolHandler
from Transport.IoHandler import IoHandler
from Transport.TcpSocket import TcpSocket

class SimpleClient(EventHandler):
    def __init__(self, end_point):
        super(SimpleClient, self).__init__()

        self._event_methods = {
            EventDispatcher.eventId('user_wait')     : self._userInteraction,
            CommunicationEndPoint.eventId('new_msg') : self._handleData
        }

        self._end_point = end_point
        if isinstance(self._end_point.getTransport(), TcpSocket):
            self._end_point.getTransport().connect()

        self._remote_addr = end_point.getTransport().getAddr()

        con_mngr = CommunicationManager()
        con_mngr.addEndPoint(self._end_point)

        dispatcher = EventDispatcher(CLIENT)
        dispatcher.registerHandler(con_mngr)
        dispatcher.registerHandler(IoHandler())
        dispatcher.registerHandler(ProtocolHandler())
        dispatcher.registerHandler(self)
        Signal.initSignals(dispatcher)

        self._timeout     = None
        self._starttime   = None
        self._request     = None
        self._response    = None
        self._sendIssued  = False


    def issue(self, request, timeout):
        self._starttime   = time.time()
        self._timeout     = timeout
        self._request     = request
        self._response    = None
        self._sendIssued  = False
        self._dispatcher[0].start(None)

        return self._response

    def getRemoteAddr(self):
        return self._remote_addr

    def getProtocol(self):
        return self._end_point.getProtocol()

    def _userInteraction(self, event):
        if self._sendIssued:
            now = time.time()

            if self._response or self._timeout <= (now - self._starttime):
                event.subject.stop()
            else:
                self.issueEvent(
                    event.subject,
                    'data_wait',
                    self._timeout - (now - self._starttime)
                )
        else:
            self.issueEvent(self._end_point, 'send_msg', self._request)
            self._sendIssued = True
        return True

    def _handleData(self, event):
        if event.data.isResponse():
            self._response = event.data
        return True

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