-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver-tornado.py
181 lines (155 loc) · 4.99 KB
/
server-tornado.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import sys
import errno
import functools
import socket
# this uses old version of ioloop because it works way faster then the new one...
from lib.tornado import ioloop, iostream
import sys
import gc
import commands
# constants
CR_LF = "\r\n"
PHASE_START = 'START'
PHASE_DATA = 'DATA'
PHASE_CONNECT = 'CONNECT'
CHAR_STAR = '*'
CHAR_DOLLAR = '$'
RET_OK = '+OK'
CMD_GET = 'GET'
CMD_SET = 'SET'
def _utf8(v):
if isinstance(v, unicode):
return v.encode('utf-8')
else:
return v
class Connection(object):
def __init__(self, stream):
self.stream = stream
self.phase = PHASE_CONNECT
self.read()
self.buf = ''
def send(self, s):
if not self.stream.closed():
self.stream.write(s + CR_LF)
def sendok(self):
self.send(RET_OK)
def sendmultival(self, v):
buf = []
buf.append('*%i' % len(v))
for i in v:
if i:
lv = _utf8(i)
try:
ln = len(lv)
except:
ln = len(str(lv))
buf.append('$%i' % ln)
buf.append(i)
else:
buf.append('$-1')
self.send(CR_LF.join(buf))
def sendval(self, v):
if v:
v = _utf8(v)
try:
ln = len(v)
except:
ln = len(str(v))
self.send('$%i' % ln)
self.send(v)
else:
self.send('$-1')
def parse_commands(self, args):
# print "cmd args", args
self.sendok()
def read(self):
self.stream.read_until(CR_LF, self.read_until_callback)
def read_until_callback(self, data):
self.eol_callback(data)
def parse_connect_line(self, line):
k = line[0]
v = line[1:].split('\r\n')[0]
if k == CHAR_STAR:
self.phase = PHASE_START
self.args = {}
self.received_arg_length = 0
self.num_args = int(v)
self.buf = ''
else:
raise Exception('commands out of order')
def parse_start_line(self, line):
if line[0] == CHAR_DOLLAR:
self.received_arg_length = self.received_arg_length + 1
self.phase = PHASE_DATA
self.wait_for_data_length = int(line[1:].split('\r\n')[0])
else:
raise Exception('commands out of order - 1')
def parse_data_line(self, line):
self.buf = self.buf + line
if len(self.buf)-2 == self.wait_for_data_length:
self.args[self.received_arg_length] = self.buf[:-2]
self.phase = PHASE_START
self.buf = ''
# did we receive everything ???
if self.received_arg_length == self.num_args:
self.parse_commands(self.args)
self.args = {}
self.phase = PHASE_CONNECT
self.received_arg_length = 0
self.num_args = 0
def eol_callback(self, line):
if self.phase == PHASE_CONNECT:
self.parse_connect_line(line)
elif self.phase == PHASE_START:
self.parse_start_line(line)
elif self.phase == PHASE_DATA:
self.parse_data_line(line)
else:
raise Exception('parser error')
# read again until we receive everything
if not self.stream.closed():
if not self.stream._read_callback:
self.read()
else:
self.debug( "closed stream" )
raise Exception("closed stream")
connections = {}
conncnt = 1
def connection_ready(sock, fd, events):
while True:
try:
connection, address = sock.accept()
except socket.error, e:
if e[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
raise
return
connection.setblocking(0)
stream = iostream.IOStream(connection, max_buffer_size=1048576)
conn = Connection(stream)
connections[len(connections)+1] = conn
def gc_connections():
# print "%s connections hanging" % len(connections)
dele = []
for i in connections:
if connections[i].stream.closed():
del connections[i].stream._read_callback
dele.append(i)
for d in dele:
del connections[d]
pass
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
sock.bind(('', 6380))
sock.listen(128)
io_loop = ioloop.IOLoop.instance()
callback = functools.partial(connection_ready, sock)
io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
try:
gcn = ioloop.PeriodicCallback(gc_connections, 5000, io_loop)
gcn.start()
io_loop.start()
except KeyboardInterrupt:
io_loop.stop()
print "exited cleanly"