Newer
Older
import socket
import threading
import socketserver
import json
import time
import sys
import sched
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()
assert(isinstance(response, dict))
self.request.sendall(json.dumps(response))
except Exception, 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, 'utf-8')
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
def connectTracker():
factory = CommandFactory({
'method': Command.METHOD_JOIN
})
command = factory.getCommand()
command.execute()
# TODO: get the status, then add the servers to the activeServers list
def findItem(server, ip, port):
pass
if __name__ == '__main__':
HOST, PORT = 'localhost', sys.argv[1]
server = ThreadedTcpServer((HOST, PORT), RequestHandler)
# start a server thread
server_thread = threading.Thread(target=server.serve_forever)
# exit the server thread when the main thread ends
server_thread.daemon = True
server_thread.start()
print("Server running on thread: ", server_thread.name)
server_thread.stop()