OLD | NEW |
1 #!/usr/bin/env python | 1 #!/usr/bin/env python |
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
3 # Use of this source code is governed by a BSD-style license that can be | 3 # Use of this source code is governed by a BSD-style license that can be |
4 # found in the LICENSE file. | 4 # found in the LICENSE file. |
5 | 5 |
6 # A simple native client in python. | 6 # A simple native client in python. |
7 # All this client does is echo the text it recieves back at the extension. | 7 # All this client does is echo the text it receives back at the extension. |
8 | 8 |
9 import sys | 9 import sys |
10 import struct | 10 import struct |
11 | 11 |
12 MESSAGE_TYPE_SEND_MESSAGE_REQUEST = 0 | |
13 MESSAGE_TYPE_SEND_MESSAGE_RESPONSE = 1 | |
14 MESSAGE_TYPE_CONNECT = 2 | |
15 MESSAGE_TYPE_CONNECT_MESSAGE = 3 | |
16 | |
17 def Main(): | 12 def Main(): |
18 message_number = 0 | 13 message_number = 0 |
19 | 14 |
20 while 1: | 15 while 1: |
21 # Read the message type (first 4 bytes). | 16 # Read the message type (first 4 bytes). |
22 type_bytes = sys.stdin.read(4) | 17 text_length_bytes = sys.stdin.read(4) |
23 | 18 |
24 if len(type_bytes) == 0: | 19 if len(text_length_bytes) == 0: |
25 break | 20 break |
26 | 21 |
27 message_type = struct.unpack('i', type_bytes)[0] | |
28 | |
29 # Read the message length (4 bytes). | 22 # Read the message length (4 bytes). |
30 text_length = struct.unpack('i', sys.stdin.read(4))[0] | 23 text_length = struct.unpack('i', text_length_bytes)[0] |
31 | 24 |
32 # Read the text (JSON object) of the message. | 25 # Read the text (JSON object) of the message. |
33 text = sys.stdin.read(text_length).decode('utf-8') | 26 text = sys.stdin.read(text_length).decode('utf-8') |
34 | 27 |
35 message_number += 1 | 28 message_number += 1 |
36 | 29 |
37 response = '{{"id": {0}, "echo": {1}}}'.format(message_number, | 30 response = '{{"id": {0}, "echo": {1}}}'.format(message_number, |
38 text).encode('utf-8') | 31 text).encode('utf-8') |
39 | |
40 # Choose the correct message type for the response. | |
41 if message_type == MESSAGE_TYPE_SEND_MESSAGE_REQUEST: | |
42 response_type = MESSAGE_TYPE_SEND_MESSAGE_RESPONSE | |
43 else: | |
44 response_type = MESSAGE_TYPE_CONNECT_MESSAGE | |
45 | 32 |
46 try: | 33 try: |
47 sys.stdout.write(struct.pack("II", response_type, len(response))) | 34 sys.stdout.write(struct.pack("I", len(response))) |
48 sys.stdout.write(response) | 35 sys.stdout.write(response) |
49 sys.stdout.flush() | 36 sys.stdout.flush() |
50 except IOError: | 37 except IOError: |
51 break | 38 break |
52 | 39 |
53 if __name__ == '__main__': | 40 if __name__ == '__main__': |
54 Main() | 41 Main() |
OLD | NEW |