Connection.py
1.79 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
"""
Associate a physical transport layer with a protocol.
Author: Georg Hopp <ghopp@spamtitan.com>
"""
from EndPoint import CommunicationEndPoint
from Transport import Transport
class Connection(CommunicationEndPoint):
_EVENTS = { 'new_con' : 0x01 }
def __init__(self, transport, protocol, read_chunk_size=8192):
super(Connection, self).__init__(transport, protocol, read_chunk_size)
self._current_msg = None
self._read_buffer = ''
self._write_buffer = ''
def hasPendingData(self):
return '' != self._write_buffer
def __iter__(self):
return self
def next(self):
"""
iterate through all available data and return all messages that can
be created from it. This is destructive for data.
"""
if not self._current_msg or self._current_msg.ready():
self._current_msg = self._protocol.createMessage(
self.getTransport().remote)
end = self._protocol.getParser().parse(
self._current_msg, self._read_buffer)
if 0 == end:
raise StopIteration
self._read_buffer = self._read_buffer[end:]
if not self._current_msg.ready():
raise StopIteration
return self._current_msg
def compose(self, message):
try:
self._write_buffer += self._protocol.getComposer().compose(message)
except Exception:
return False
return True
def appendReadData(self, data_remote):
self._read_buffer += data_remote[0]
def nextWriteData(self):
buf = self._write_buffer
self._write_buffer = ''
return (buf, None)
def appendWriteData(self, data_remote):
self._write_buffer += data_remote[0]
# vim: set ft=python et ts=8 sw=4 sts=4: