Newer
Older
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
import socket
import threading
import socketserver
import json
import time
from command import CommandFactory, Command
class RequestHandler(socketserver.BaseRequestHandler):
BUFSIZE = 4096
def handle(self):
data = self.getData()
# check if the request is not empty (aka pings)
if not data:
pass
else:
try:
jsonObject = json.loads(data)
# throw it into the command processor
factory = CommandFactory(jsonObject)
command = factory.getCommand()
command.execute()
response = command.getStatus()
self.request.sendall(json.dumps(response))
except ValueError, e:
pass # TODO: log the error
def getData(self, timeout = 3):
total_data = []
end = False
self.request.setblocking(0)
begin = time.time()
while not end:
# if got some data, break after wait sec
if total_data and time.time() - begin > timeout:
end = True
else:
# if no data, break after 2x the timeout
if time.time() - begin > timeout * 2:
end = True
else:
try:
data = self.request.recv(RequestHandler.BUFSIZE, 'ascii')
if not data:
time.sleep(0.1)
else:
total_data.append(data)
begin = time.time()
except Exception, e:
# TODO: log the error
end = True
return ''.join(total_data)
class ThreadedTcpServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == '__main__':
pass