(self)
| 63 | self.clients = {} |
| 64 | |
| 65 | def run(self): |
| 66 | while True: |
| 67 | line = "" |
| 68 | client_id = "" |
| 69 | try: |
| 70 | line = input().strip() |
| 71 | if not line: |
| 72 | continue |
| 73 | # parse PIME requests (one request per line): |
| 74 | # request format: "<client_id>|<JSON string>\n" |
| 75 | # response format: "PIME_MSG|<client_id>|<JSON string>\n" |
| 76 | client_id, msg_text = line.split('|', maxsplit=1) |
| 77 | msg = json.loads(msg_text) |
| 78 | client = self.clients.get(client_id) |
| 79 | if not client: |
| 80 | # create a Client instance for the client |
| 81 | client = Client(self) |
| 82 | self.clients[client_id] = client |
| 83 | print("new client:", client_id) |
| 84 | if msg.get("method") == "close": # special handling for closing a client |
| 85 | self.remove_client(client_id) |
| 86 | else: |
| 87 | ret = client.handleRequest(msg) |
| 88 | # Send the response to the client via stdout |
| 89 | # one response per line in the format "PIME_MSG|<client_id>|<json reply>" |
| 90 | reply_line = '|'.join(["PIME_MSG", client_id, json.dumps(ret, ensure_ascii=False)]) |
| 91 | print(reply_line) |
| 92 | except EOFError: |
| 93 | # stop the server |
| 94 | break |
| 95 | except Exception as e: |
| 96 | print("ERROR:", e, line) |
| 97 | # print the exception traceback for ease of debugging |
| 98 | traceback.print_exc() |
| 99 | # generate an empty output containing {success: False} to prevent the client from being blocked |
| 100 | reply_line = '|'.join(["PIME_MSG", client_id, '{"success":false}']) |
| 101 | print(reply_line) |
| 102 | # Just terminate the python server process if any unknown error happens. |
| 103 | # The python server will be restarted later by PIMELauncher. |
| 104 | sys.exit(1) |
| 105 | |
| 106 | def remove_client(self, client_id): |
| 107 | print("client disconnected:", client_id) |
no test coverage detected