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():
73 return self.session.connection().recv(2048)
78 raw_buffer = self.message.find('\n')
82 raw_command = self.message[0:raw_buffer].strip()
83 self.message = self.message[raw_buffer + 1:]
84 if raw_command == 'quit':
89 command = json.loads(raw_command)
91 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
95 # Try to load vital fields, and return an error if
97 message_id = command['id']
98 method = command['method']
100 # Return an error JSON in response.
101 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
103 self.dispatcher.push_request(self.session,command)
107 class TcpServer(threading.Thread):
109 def __init__(self, dispatcher, host, port):
110 self.shared = dispatcher.shared
111 self.dispatcher = dispatcher.request_dispatcher
112 threading.Thread.__init__(self)
116 self.lock = threading.Lock()
119 print "TCP server started."
120 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
121 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
122 sock.bind((self.host, self.port))
124 while not self.shared.stopped():
125 session = TcpSession(*sock.accept())
126 self.dispatcher.add_session(session)
127 self.dispatcher.collect_garbage()
128 client_req = TcpClientRequestor(self.dispatcher, session)