7 from processor import Session, Dispatcher
9 class TcpSession(Session):
11 def __init__(self, connection, address):
12 self._connection = connection
13 self.address = address
14 Session.__init__(self)
15 print "New session", address
19 raise Exception("Session was stopped")
21 return self._connection
24 self._connection.close()
25 print "Terminating connection:", self.address[0]
29 def send_response(self, response):
30 raw_response = json.dumps(response)
31 # Possible race condition here by having session
33 # I assume Python connections are thread safe interfaces
35 connection = self.connection()
36 connection.send(raw_response + "\n")
42 class TcpClientRequestor(threading.Thread):
44 def __init__(self, dispatcher, session):
45 self.shared = dispatcher.shared
46 self.dispatcher = dispatcher
48 self.session = session
49 threading.Thread.__init__(self)
52 while not self.shared.stopped():
71 return self.session.connection().recv(1024)
76 raw_buffer = self.message.find('\n')
80 raw_command = self.message[0:raw_buffer].strip()
81 self.message = self.message[raw_buffer + 1:]
82 if raw_command == 'quit':
87 command = json.loads(raw_command)
89 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
93 # Try to load vital fields, and return an error if
95 message_id = command['id']
96 method = command['method']
98 # Return an error JSON in response.
99 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
101 self.dispatcher.push_request(self.session,command)
105 class TcpServer(threading.Thread):
107 def __init__(self, dispatcher, host, port):
108 self.shared = dispatcher.shared
109 self.dispatcher = dispatcher.request_dispatcher
110 threading.Thread.__init__(self)
114 self.lock = threading.Lock()
117 print "TCP server started."
118 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
119 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
120 sock.bind((self.host, self.port))
122 while not self.shared.stopped():
123 session = TcpSession(*sock.accept())
124 client_req = TcpClientRequestor(self.dispatcher, session)
126 self.dispatcher.add_session(session)
127 self.dispatcher.collect_garbage()