OLD | NEW |
| (Empty) |
1 # Copyright 2013 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 import json | |
6 import logging | |
7 import socket | |
8 | |
9 from telemetry.core import util | |
10 from telemetry.core.chrome import websocket | |
11 | |
12 class WebSocketBrowserConnection(object): | |
13 """Represents a websocket connection to the browser for backends | |
14 which use one.""" | |
15 | |
16 def __init__(self, devtools_port): | |
17 debugger_url = 'ws://localhost:%i/devtools/browser' % devtools_port | |
18 self._socket = websocket.create_connection(debugger_url) | |
19 self._next_request_id = 0 | |
20 self._cur_socket_timeout = 0 | |
21 | |
22 def Close(self): | |
23 if self._socket: | |
24 self._socket.close() | |
25 self._socket = None | |
26 | |
27 def SendRequest(self, req, timeout=10): | |
28 self._SetTimeout(timeout) | |
29 req['id'] = self._next_request_id | |
30 self._next_request_id += 1 | |
31 data = json.dumps(req) | |
32 logging.debug('will send [%s]', data) | |
33 self._socket.send(data) | |
34 | |
35 def SyncRequest(self, req, timeout=10): | |
36 self.SendRequest(req, timeout) | |
37 while True: | |
38 try: | |
39 data = self._socket.recv() | |
40 except (socket.error, websocket.WebSocketException): | |
41 raise util.TimeoutException( | |
42 "Timed out waiting for reply. This is unusual.") | |
43 res = json.loads(data) | |
44 logging.debug('got [%s]', data) | |
45 if res['id'] != req['id']: | |
46 logging.debug('Dropped reply: %s', json.dumps(res)) | |
47 continue | |
48 return res | |
49 | |
50 @property | |
51 def socket(self): | |
52 """Returns the socket for raw access. Please be sure you know what | |
53 you are doing.""" | |
54 return self._socket | |
55 | |
56 def _SetTimeout(self, timeout): | |
57 if self._cur_socket_timeout != timeout: | |
58 self._socket.settimeout(timeout) | |
59 self._cur_socket_timeout = timeout | |
OLD | NEW |