SimpleClient.py
2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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: