Python websocket.WebSocketTimeoutException() Examples

The following are 30 code examples of websocket.WebSocketTimeoutException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module websocket , or try the search function .
Example #1
Source File: test_websocket.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #2
Source File: reconnecting_websocket.py    From neptune-client with Apache License 2.0 6 votes vote down vote up
def recv(self):
        if not self.client.connected:
            self._try_to_establish_connection()
        while self._is_active():
            try:
                data = self.client.recv()
                self._on_successful_connect()
                return data
            except WebSocketTimeoutException:
                raise
            except WebSocketConnectionClosedException:
                if self._is_active():
                    self._handle_lost_connection()
                else:
                    raise
            except WebsocketNotConnectedException:
                if self._is_active():
                    self._handle_lost_connection()
            except Exception:
                if self._is_active():
                    self._handle_lost_connection() 
Example #3
Source File: transport.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __connect_to_tab(self, tab_key):
		assert tab_key not in self.soclist

		cr_tab_meta = self._get_cr_tab_meta_for_key(tab_key)

		if not 'webSocketDebuggerUrl' in cr_tab_meta:
			raise cr_exceptions.ChromeConnectFailure("Tab %s has no 'webSocketDebuggerUrl' (%s)" % (tab_key, self.tablist))

		wsurl = cr_tab_meta['webSocketDebuggerUrl']

		try:
			self.log.info("Setting up websocket connection for key '%s'", tab_key)
			self.soclist[tab_key] = websocket.create_connection(wsurl)
			self.soclist[tab_key].settimeout(self.websocket_timeout)

		except (socket.timeout, websocket.WebSocketTimeoutException):
			raise cr_exceptions.ChromeCommunicationsError("Could not connect to remote chromium.") 
Example #4
Source File: test_websocket.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #5
Source File: test_websocket.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #6
Source File: transport.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ___recv(self, tab_key, timeout=None):

		try:
			if timeout:
				self.soclist[tab_key].settimeout(timeout)

			tmp = self.soclist[tab_key].recv()
			self.log.debug("		Received: '%s'", tmp)

			decoded = json.loads(tmp)
			return decoded
		except (socket.timeout, websocket.WebSocketTimeoutException):
			return None
		except websocket.WebSocketConnectionClosedException:
			raise cr_exceptions.ChromeCommunicationsError("Websocket appears to have been closed. Is the"
				" remote chromium instance dead?")
		finally:
			self.soclist[tab_key].settimeout(self.websocket_timeout) 
Example #7
Source File: bitmex_websocket.py    From archon with MIT License 6 votes vote down vote up
def __connect(self, wsURL, symbol):
        '''Connect to the websocket in a thread.'''
        self.logger.debug("Starting thread")

        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth())

        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.daemon = True
        self.wst.start()
        self.logger.debug("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            sleep(1)
            conn_timeout -= 1
        if not conn_timeout:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.') 
Example #8
Source File: test_websocket.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #9
Source File: test_websocket.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #10
Source File: test_websocket.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #11
Source File: test_websocket.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #12
Source File: test_websocket.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #13
Source File: py_bitflyer_jsonrpc.py    From py_bitflyer_jsonrpc with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __connect(self, wsURL, symbol):
        '''Connect to the websocket in a thread.'''
        self.logger.debug("Starting thread")

        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=None)

        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.daemon = True
        self.wst.start()
        self.logger.debug("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            sleep(1)
            conn_timeout -= 1
        if not conn_timeout:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.') 
Example #14
Source File: hitbtc.py    From bitex with MIT License 6 votes vote down vote up
def _trade_thread(self):
        try:
            conn = create_connection(self.trader_addr)
        except Exception:
            log.exception('Trader Thread Error!')
            self._controller_q.put('restart_trader')
            return

        while self.running:
            try:
                data = conn.recv()
            except WebSocketTimeoutException:
                self._controller_q.put('restart_data')
                return
            self.data_q.put(json.loads(data))

            try:
                payload = self.trade_command_q.get()
            except Empty:
                continue

            try:
                conn.send(self.sign(payload))
            except (WebSocketTimeoutException, ConnectionResetError):
                continue 
Example #15
Source File: hitbtc.py    From bitex with MIT License 6 votes vote down vote up
def _data_thread(self):
        try:
            conn = create_connection(self.addr)
        except Exception:
            self._controller_q.put('restart_data')
            return

        while self.running:
            try:
                data = conn.recv()
                data = json.loads(data)
            except WebSocketTimeoutException:
                self._controller_q.put('restart_data')
                return
            try:
                pair = data['MarketDataIncrementalRefresh']['symbol']
                endpoint = 'MarketDataIncrementalRefresh'
            except KeyError:
                pair = data['MarketDataSnapshotFullRefresh']['symbol']
                endpoint = 'MarketDataSnapshotFullRefresh'
            self.data_q.put((endpoint, pair, data[endpoint], time.time())) 
Example #16
Source File: bitmex_websocket_com.py    From SyBrain with GNU General Public License v3.0 6 votes vote down vote up
def __connect(self, wsURL, symbol):
        '''Connect to the websocket in a thread.'''
        self.logger.debug("Starting thread")

        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth())

        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.setDaemon(True)
        self.wst.start()
        self.logger.debug("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            sleep(1)
            conn_timeout -= 1
        if not conn_timeout:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.') 
Example #17
Source File: test_websocket.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #18
Source File: test_websocket.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #19
Source File: test_websocket.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv() 
Example #20
Source File: test_websocket.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1) 
Example #21
Source File: __init__.py    From ChromeHeadlessInterface with GNU General Public License v3.0 5 votes vote down vote up
def recv_by_special_id(self, command_id=None):

        if command_id:
            expected_id = command_id
        else:
            expected_id = self._command_id

        ws_result = []
        ws_instance = self._tab.get("ws_instance")

        while True:
            try:
                result = ws_instance.recv()
            except websocket.WebSocketTimeoutException:
                return ws_result

            if self._debug:
                print("[DEBUG] result: {0}".format(result))
            if not result:
                return ws_result

            # 提取结果
            ws_result.append(result)

            # 调用用户定义的事件
            formatted_result = json.loads(result)
            event_name = formatted_result.get("method")
            params = formatted_result.get("params")
            self._call_event_listener(event_name, params)

            # 查找结束标志
            if int(formatted_result.get("id", 0)) == expected_id-1:
                break
        return ws_result 
Example #22
Source File: transport.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send(self, command, tab_key, params=None):
		'''
		Send command `command` with optional parameters `params` to the
		remote chrome instance.

		The command `id` is automatically added to the outgoing message.

		return value is the command id, which can be used to match a command
		to it's associated response.
		'''
		self.__check_open_socket(tab_key)

		sent_id = self.msg_id

		command = {
				"id": self.msg_id,
				"method": command,
			}

		if params:
			command["params"] = params
		navcom = json.dumps(command)


		# self.log.debug("		Sending: '%s'", navcom)
		try:
			self.soclist[tab_key].send(navcom)
		except (socket.timeout, websocket.WebSocketTimeoutException):
			raise cr_exceptions.ChromeCommunicationsError("Failure sending command to chromium.")
		except websocket.WebSocketConnectionClosedException:
			raise cr_exceptions.ChromeCommunicationsError("Websocket appears to have been closed. Is the"
				" remote chromium instance dead?")


		self.msg_id += 1
		return sent_id 
Example #23
Source File: mirapi.py    From ewm-cloud-robotics with Apache License 2.0 5 votes vote down vote up
def send_ws_message(self, message: Dict) -> None:
        """Send a message via websocket."""
        try:
            # Open websocket connection
            wsclient = create_connection('ws://{host}:9090'.format(
                host=self.mirconfig.host), timeout=5)
            wsclient.send(json.dumps(message))
        except (WebSocketTimeoutException, TimeoutError):
            msg = 'Connection to rosbridge websocket timed out'
            _LOGGER.debug(msg)
            raise requests.Timeout(msg)
        else:
            wsclient.close() 
Example #24
Source File: client.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def _ws_events(ws_conn, message, snapshot, since, on_message, on_error):
    """Process websocket events."""
    # Pylint complains too many nested blocks.
    #
    # pylint: disable=R0101
    last_timestamp = since
    subscription_msg = {'since': since,
                        'snapshot': snapshot}
    subscription_msg.update(message)

    try:
        ws_conn.send(json.dumps(subscription_msg))
        while True:
            try:
                reply = ws_conn.recv()
                if not reply:
                    break

                result = json.loads(reply)
                if '_error' in result:
                    if on_error:
                        on_error(result)
                    break

                last_timestamp = result.get('when', time.time())
                if on_message:
                    if not on_message(result):
                        break
            except ws_client.WebSocketTimeoutException:
                ws_conn.ping()

    except ws_client.WebSocketConnectionClosedException as err:
        _LOGGER.debug('ws connection closed, will retry: %s.', str(err))
        raise _RetryError(last_timestamp)
    finally:
        ws_conn.close() 
Example #25
Source File: plugin.py    From python-tripleoclient with Apache License 2.0 5 votes vote down vote up
def wait_for_messages(self, timeout=None):
        """Wait for messages on a Zaqar queue

        A timeout can be provided in seconds, if no timeout is provided it
        will block forever until a message is received. If no message is
        received (for example, Zaqar is down) then it will block until manually
        killed.

        If no timeout is provided this method will never stop waiting for new
        messages. It is the responsibility of the consumer to stop consuming
        messages.
        """

        if timeout is None:
            LOG.warning("Waiting for messages on queue '{}' with no timeout."
                        .format(self._queue_name))

        try:
            self._ws.settimeout(timeout)
            while True:
                message = self.recv()
                LOG.debug(message)
                yield message['body']['payload']

        except websocket.WebSocketTimeoutException:
            raise exceptions.WebSocketTimeout()
        except websocket.WebSocketConnectionClosedException:
            raise exceptions.WebSocketConnectionClosed() 
Example #26
Source File: media.py    From olympe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _websocket_exc_handler(method):
        def wrapper(self, *args, **kwds):
            try:
                return method(self, *args, **kwds)
            except (TimeoutError, websocket.WebSocketTimeoutException):
                self.logger.warning("Websocket timeout")
            except (ConnectionError, websocket.WebSocketException) as e:
                # If we lose the connection we must reinitialize our state
                self.logger.error(str(e))
                self._reset_state()
            except Exception as e:
                self.logger.exception("Websocket callback unhandled exception")
                self._reset_state()

        return wrapper 
Example #27
Source File: __init__.py    From ChromeHeadlessInterface with GNU General Public License v3.0 5 votes vote down vote up
def recv_until_string(self, expected_string):

        ws_result = []
        ws_instance = self._tab.get("ws_instance")

        while True:
            try:
                result = ws_instance.recv()
            except websocket.WebSocketTimeoutException:
                return ws_result

            if self._debug:
                print("[DEBUG] result: {0}".format(result))
            if not result:
                return ws_result

            # 提取结果
            ws_result.append(result)

            # 调用用户定义的事件
            formatted_result = json.loads(result)
            event_name = formatted_result.get("method")
            params = formatted_result.get("params")
            self._call_event_listener(event_name, params)

            # 查找结束标志
            if expected_string in result:
                break
        return ws_result 
Example #28
Source File: bitmex_ws.py    From archon with MIT License 5 votes vote down vote up
def __connect(self, wsURL, symbol):
        '''Connect to the websocket in a thread.'''
        self.logger.debug(".....Starting thread")

        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth())

        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.daemon = True
        self.wst.start()
        self.logger.debug("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            sleep(1)            
            conn_timeout -= 1

        if not conn_timeout:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')

        self.logger.debug("exit connect") 
Example #29
Source File: old_bitmex_ws.py    From archon with MIT License 5 votes vote down vote up
def __connect(self, wsURL, symbol):
        '''Connect to the websocket in a thread.'''
        self.logger.debug(".....Starting thread")

        self.ws = websocket.WebSocketApp(wsURL,
                                         on_message=self.__on_message,
                                         on_close=self.__on_close,
                                         on_open=self.__on_open,
                                         on_error=self.__on_error,
                                         header=self.__get_auth())

        self.wst = threading.Thread(target=lambda: self.ws.run_forever())
        self.wst.daemon = True
        self.wst.start()
        self.logger.debug("Started thread")

        # Wait for connect before continuing
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            sleep(1)            
            conn_timeout -= 1

        if not conn_timeout:
            self.logger.error("Couldn't connect to WS! Exiting.")
            self.exit()
            raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')

        self.logger.debug("exit connect") 
Example #30
Source File: chromeboy.py    From falsy with MIT License 5 votes vote down vote up
def run1(self, payload):
        data = None
        browser = None
        begin_time = datetime.datetime.now()
        retry = payload.get('retried', False)
        try:
            socket_timeout = payload.get('sockettimeout') or self._socket_timeout
            browser = websocket.create_connection(self._browser_url, timeout=socket_timeout)
            data = self.run1_core(payload, browser, begin_time)
            return data
        except websocket.WebSocketTimeoutException as e:
            if retry:
                error_data = {
                    'state': 'critical',
                    'error_code': -6,
                    'error_desc': str(type(e)) + ': ' + str(e)
                }
                ret = self.crawl_info(error_data, payload, begin_time)
                return ret
            else:
                sleep(payload.get('retry_sleep', 3))
                payload['sockettimeout'] = int(payload.get('sockettimeout') or self._socket_timeout) + payload.get(
                    'retry_extra', 10)
                payload['loadtimeout'] = int(payload.get('loadtimeout') or self._socket_timeout) + payload.get('retry_extra',
                                                                                                               10)
                payload['retried'] = True
                return self.run1_core(payload, browser=browser, begin_time=begin_time)
        except Exception as e:
            error_data = {
                'state': 'critical',
                'error_code': -7,
                'error_desc': str(type(e)) + ': ' + str(e)
            }
            ret = self.crawl_info(error_data, payload, begin_time)
            return ret

        finally:
            if browser is not None:
                browser.close()