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
|
import sys
from twisted.internet.protocol import Protocol
class LineProtocol(Protocol):
delimiter = "\n"
buffer = ""
def dataReceived(self, bytes):
self.buffer += bytes
lines = self.buffer.split(self.delimiter)
self.buffer = lines.pop()
for line in lines:
self.lineReceived(line)
def sendLine(self, line):
self.transport.write(line + self.delimiter)
def lineReceived(self, line):
pass
class Echoer(LineProtocol):
def lineReceived(self, line):
self.sendLine(line)
def main():
echo = Echoer()
echo.makeConnection(sys.stdout)
while True:
byte = sys.stdin.read(1)
if not byte:
break
echo.dataReceived(byte)
def test():
from StringIO import StringIO
output = StringIO()
echo = Echoer()
echo.makeConnection(output)
echo.dataReceived("foo\n")
echo.dataReceived("bar\n")
assert output.getvalue() == "foo\nbar\n"
test()
|