7 from processor import Session, Dispatcher, timestr
9 class TcpSession(Session):
11 def __init__(self, connection, address):
12 Session.__init__(self)
13 self._connection = connection
14 self.address = address[0]
15 self.name = "TCP session"
19 raise Exception("Session was stopped")
21 return self._connection
24 self._connection.close()
25 #print "Terminating connection:", self.address
29 def send_response(self, response):
30 data = json.dumps(response) + "\n"
31 # Possible race condition here by having session
33 # I assume Python connections are thread safe interfaces
35 connection = self.connection()
37 l = connection.send(data)
44 class TcpClientRequestor(threading.Thread):
46 def __init__(self, dispatcher, session):
47 self.shared = dispatcher.shared
48 self.dispatcher = dispatcher
50 self.session = session
51 threading.Thread.__init__(self)
54 while not self.shared.stopped():
58 self.session.time = time.time()
75 return self.session.connection().recv(2048)
80 raw_buffer = self.message.find('\n')
84 raw_command = self.message[0:raw_buffer].strip()
85 self.message = self.message[raw_buffer + 1:]
86 if raw_command == 'quit':
91 command = json.loads(raw_command)
93 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
97 # Try to load vital fields, and return an error if
99 message_id = command['id']
100 method = command['method']
102 # Return an error JSON in response.
103 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
105 self.dispatcher.push_request(self.session,command)
109 class TcpServer(threading.Thread):
111 def __init__(self, dispatcher, host, port):
112 self.shared = dispatcher.shared
113 self.dispatcher = dispatcher.request_dispatcher
114 threading.Thread.__init__(self)
118 self.lock = threading.Lock()
121 print "TCP server started."
122 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
123 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
124 sock.bind((self.host, self.port))
126 while not self.shared.stopped():
127 session = TcpSession(*sock.accept())
128 self.dispatcher.add_session(session)
129 self.dispatcher.collect_garbage()
130 client_req = TcpClientRequestor(self.dispatcher, session)