7 from processor import Session, Dispatcher, timestr
9 class TcpSession(Session):
11 def __init__(self, connection, address, use_ssl, ssl_certfile, ssl_keyfile):
12 Session.__init__(self)
13 print connection, address, use_ssl
16 self._connection = ssl.wrap_socket(
19 certfile=ssl_certfile,
21 ssl_version=ssl.PROTOCOL_SSLv23)
23 self._connection = connection
25 self.address = address[0]
30 raise Exception("Session was stopped")
32 return self._connection
35 self._connection.close()
36 #print "Terminating connection:", self.address
40 def send_response(self, response):
41 data = json.dumps(response) + "\n"
42 # Possible race condition here by having session
44 # I assume Python connections are thread safe interfaces
46 connection = self.connection()
48 l = connection.send(data)
55 class TcpClientRequestor(threading.Thread):
57 def __init__(self, dispatcher, session):
58 self.shared = dispatcher.shared
59 self.dispatcher = dispatcher
61 self.session = session
62 threading.Thread.__init__(self)
65 while not self.shared.stopped():
69 self.session.time = time.time()
86 return self.session.connection().recv(2048)
91 raw_buffer = self.message.find('\n')
95 raw_command = self.message[0:raw_buffer].strip()
96 self.message = self.message[raw_buffer + 1:]
97 if raw_command == 'quit':
102 command = json.loads(raw_command)
104 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
108 # Try to load vital fields, and return an error if
110 message_id = command['id']
111 method = command['method']
113 # Return an error JSON in response.
114 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
116 self.dispatcher.push_request(self.session,command)
120 class TcpServer(threading.Thread):
122 def __init__(self, dispatcher, host, port, use_ssl, ssl_certfile, ssl_keyfile):
123 self.shared = dispatcher.shared
124 self.dispatcher = dispatcher.request_dispatcher
125 threading.Thread.__init__(self)
129 self.lock = threading.Lock()
130 self.use_ssl = use_ssl
131 self.ssl_keyfile = ssl_keyfile
132 self.ssl_certfile = ssl_certfile
135 print "TCP server started.", self.use_ssl
136 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
137 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
138 sock.bind((self.host, self.port))
140 while not self.shared.stopped():
141 session = TcpSession(*sock.accept(), use_ssl=self.use_ssl, ssl_certfile=self.ssl_certfile, ssl_keyfile=self.ssl_keyfile)
142 self.dispatcher.add_session(session)
143 self.dispatcher.collect_garbage()
144 client_req = TcpClientRequestor(self.dispatcher, session)