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