ProtocolHandler.py
2.67 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
"""
@author Georg Hopp
"""
from contextlib import contextmanager
from Connection import Connection
from Event.EventHandler import EventHandler
class ProtocolHandler(EventHandler):
def __init__(self):
super(ProtocolHandler, self).__init__()
self._event_methods = {
Connection.eventId('new_data') : self._parse,
Connection.eventId('send_msg') : self._compose,
Connection.eventId('upgrade') : self._upgrade
}
def _parse(self, event):
for message in event.subject:
try:
"""
only because websockets currently have no message
class which would handle this correctly...so we
just ignore this problem here.
"""
if message.isCloseMessage():
self.issueEvent(event.subject, 'new_msg', message)
if message.isResponse():
event.subject.setClose() # setting this results in
# closing the endpoint as
# soon as everything was tried
elif message.isUpgradeMessage():
if message.isRequest():
protocol = event.subject.getProtocol()
response = protocol.createUpgradeResponse(message)
self.issueEvent(event.subject, 'send_msg', response)
else:
protocol = event.subject.getProtocol()
self.issueEvent(event.subject, 'upgrade', message)
else:
self.issueEvent(event.subject, 'new_msg', message)
except Exception:
pass
def _compose(self, event):
endpoint = event.subject
message = event.data
if endpoint.compose(message):
self.issueEvent(endpoint, 'write_ready')
try:
"""
only because websockets currently have no message
class which would handle this correctly...so we
just ignore this problem here.
"""
if message.isResponse():
if message.isCloseMessage():
endpoint.setClose()
if message.isUpgradeMessage():
self.issueEvent(endpoint, 'upgrade', message)
except Exception:
pass
def _upgrade(self, event):
protocol = event.subject.getProtocol()
new_proto = protocol.upgrade(event.data)
event.subject.setProtocol(new_proto)
# vim: set ft=python et ts=4 sw=4 sts=4: