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.
9 from telemetry.core import util
10 from telemetry.core.backends.chrome import websocket
12 class WebSocketBrowserConnection(object):
13 """Represents a websocket connection to the browser for backends
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
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)
35 def SyncRequest(self, req, timeout=10):
36 self.SendRequest(req, timeout)
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))
52 """Returns the socket for raw access. Please be sure you know what
56 def _SetTimeout(self, timeout):
57 if self._cur_socket_timeout != timeout:
58 self._socket.settimeout(timeout)
59 self._cur_socket_timeout = timeout