當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.ConnectionClosed方法代碼示例

本文整理匯總了Python中websockets.exceptions.ConnectionClosed方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.ConnectionClosed方法的具體用法?Python exceptions.ConnectionClosed怎麽用?Python exceptions.ConnectionClosed使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在websockets.exceptions的用法示例。


在下文中一共展示了exceptions.ConnectionClosed方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _receive

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _receive(self) -> str:
        """Wait the next message from the websocket connection and log the answer
        """

        # We should always have an active websocket connection here
        assert self.websocket is not None

        # Wait for the next websocket frame. Can raise ConnectionClosed
        data: Data = await self.websocket.recv()

        # websocket.recv() can return either str or bytes
        # In our case, we should receive only str here
        if not isinstance(data, str):
            raise TransportProtocolError("Binary data received in the websocket")

        answer: str = data

        log.info("<<< %s", answer)

        return answer 
開發者ID:graphql-python,項目名稱:gql,代碼行數:22,代碼來源:websockets.py

示例2: _attempt_connection

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _attempt_connection(self, fn_name, arg=None):
        fn = self._interface.node.__getattribute__(fn_name)
        self._interface.node.thread_shutdown = True
        self._interface.node.heartbeat_thread.join()
        self._interface.node.thread_shutdown = False
        try:
            #debug(); pdb.set_trace()
            if arg:
                return fn(arg)
            else:
                return fn()
        except StaleBlockchain:
            self._scene.add_effect( MessageDialog(self._screen, "Stale blockchain on selected Node"))
            return
        #except (AttributeError, InvalidStatusCode, ConnectionClosed, TimeoutError, OSError) as e: #Timeout
        #    self._scene.add_effect( MessageDialog(self._screen, "Could not connect to node ({})".format(str(e.__class__))))
        #    return
 
        self._interface.node.start_heartbeat_thread() 
開發者ID:kayagoban,項目名稱:shadowlands,代碼行數:21,代碼來源:network_options.py

示例3: _feed_buffer

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _feed_buffer(self, n=1):
        """
        Feed the data buffer by reading a Websocket message.
        :param n: if given, feed buffer until it contains at least n bytes
        """
        buffer = bytearray(self._stream.read())
        while len(buffer) < n:
            try:
                message = yield from self._protocol.recv()
            except ConnectionClosed:
                message = None
            if message is None:
                break
            if not isinstance(message, bytes):
                raise TypeError("message must be bytes")
            buffer.extend(message)
        self._stream = io.BytesIO(buffer) 
開發者ID:beerfactory,項目名稱:hbmqtt,代碼行數:19,代碼來源:adapters.py

示例4: _inner_messages

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    if ((msg != "{\"event\":\"heartbeat\"}" and
                         "\"event\":\"systemStatus\"" not in msg and
                         "\"event\":\"subscriptionStatus\"" not in msg)):
                        yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:26,代碼來源:kraken_api_order_book_data_source.py

示例5: _inner_messages

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close()

    # get required data to create a websocket request 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:25,代碼來源:kucoin_api_order_book_data_source.py

示例6: _inner_messages

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _inner_messages(self,
                              ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:23,代碼來源:bamboo_relay_api_order_book_data_source.py

示例7: _get_response

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _get_response(self, ws: websockets.WebSocketClientProtocol):
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    self._last_recv_time = time.time()
                    yield msg
                except asyncio.TimeoutError:
                    raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:18,代碼來源:bitfinex_api_user_stream_data_source.py

示例8: _inner_messages

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
        # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
        try:
            while True:
                try:
                    msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
                    yield msg
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await ws.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await ws.close() 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:22,代碼來源:dolomite_api_order_book_data_source.py

示例9: _messages

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _messages(self) -> AsyncIterable[Any]:
        try:
            while True:
                try:
                    raw_msg_str: str = await asyncio.wait_for(self._client.recv(), timeout=self.MESSAGE_TIMEOUT)
                    raw_msg = ujson.loads(raw_msg_str)

                    yield raw_to_response(raw_msg)
                except asyncio.TimeoutError:
                    try:
                        pong_waiter = await self._client.ping()
                        await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
                    except asyncio.TimeoutError:
                        raise
        except asyncio.TimeoutError:
            self.logger().warning("WebSocket ping timed out. Going to reconnect...")
            return
        except ConnectionClosed:
            return
        finally:
            await self.disconnect()

    # emit messages 
開發者ID:CoinAlpha,項目名稱:hummingbot,代碼行數:25,代碼來源:bitcoin_com_websocket.py

示例10: _send

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _send(self, message: str) -> None:
        """Send the provided message to the websocket connection and log the message
        """

        if not self.websocket:
            raise TransportClosed(
                "Transport is not connected"
            ) from self.close_exception

        try:
            await self.websocket.send(message)
            log.info(">>> %s", message)
        except ConnectionClosed as e:
            await self._fail(e, clean_close=False)
            raise e 
開發者ID:graphql-python,項目名稱:gql,代碼行數:17,代碼來源:websockets.py

示例11: get_server_handler

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def get_server_handler(request):
    """Get the server handler.

    Either get it from test or use the default server handler
    if the test provides only an array of answers.
    """

    if isinstance(request.param, types.FunctionType):
        server_handler = request.param

    else:
        answers = request.param

        async def default_server_handler(ws, path):

            try:
                await WebSocketServer.send_connection_ack(ws)
                query_id = 1

                for answer in answers:
                    result = await ws.recv()
                    print(f"Server received: {result}")

                    if isinstance(answer, str) and "{query_id}" in answer:
                        answer_format_params = {"query_id": query_id}
                        formatted_answer = answer.format(**answer_format_params)
                    else:
                        formatted_answer = answer

                    await ws.send(formatted_answer)
                    await WebSocketServer.send_complete(ws, query_id)
                    query_id += 1

                await WebSocketServer.wait_connection_terminate(ws)
                await ws.wait_closed()
            except ConnectionClosed:
                pass

        server_handler = default_server_handler

    return server_handler 
開發者ID:graphql-python,項目名稱:gql,代碼行數:43,代碼來源:conftest.py

示例12: _run_socket

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def _run_socket(self):
        retries = 0
        sId =  len(self.sockets)
        s = Socket(sId)
        self.sockets[sId] = s
        loop = asyncio.get_event_loop()
        while retries < self.max_retries and self.attempt_retry:
            try:
                async with websockets.connect(self.host) as websocket:
                    self.sockets[sId].set_websocket(websocket)
                    self.sockets[sId].set_connected()
                    self.logger.info("Websocket connected to {}".format(self.host))
                    retries = 0
                    while True:
                        # optimization - wait 0 seconds to force the async queue
                        # to be cleared before continuing
                        await asyncio.sleep(0)
                        message = await websocket.recv()
                        await self.on_message(sId, message)
            except (ConnectionClosed, socket.error) as e:
                self.sockets[sId].set_disconnected()
                if self.sockets[sId].isAuthenticated:
                    self.sockets[sId].set_unauthenticated()
                self._emit('disconnected')
                if (not self.attempt_retry):
                    return
                self.logger.error(str(e))
                retries += 1
                # wait 5 seconds befor retrying
                self.logger.info("Waiting 5 seconds before retrying...")
                await asyncio.sleep(5)
                self.logger.info("Reconnect attempt {}/{}".format(retries, self.max_retries))
        self.logger.info("Unable to connect to websocket.")
        self._emit('stopped') 
開發者ID:bitfinexcom,項目名稱:bitfinex-api-py,代碼行數:36,代碼來源:generic_websocket.py

示例13: recv

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def recv(self):
        if not self.responses:
            await asyncio.sleep(1)  # delay to give test time to finish
            raise ConnectionClosed(0, 'ran out of responses')
        return json.dumps(self.responses.popleft()) 
開發者ID:juju,項目名稱:python-libjuju,代碼行數:7,代碼來源:test_connection.py

示例14: connect_schwifty

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def connect_schwifty(self):
        self.schwifty = await SchwiftyWebsocket.create(
            self.shard,
            self
        )

        while not self.is_closed:
            try:
                await self.schwifty.poll_event()
            except (ConnectionClosed, asyncio.TimeoutError) as e:
                await asyncio.sleep(1)
                self.schwifty = await SchwiftyWebsocket.create(
                    self.shard,
                    self
                ) 
開發者ID:cookkkie,項目名稱:mee6,代碼行數:17,代碼來源:mee6.py

示例15: chrome_tab

# 需要導入模塊: from websockets import exceptions [as 別名]
# 或者: from websockets.exceptions import ConnectionClosed [as 別名]
def chrome_tab():
    """Ensure Chrome is running
    """
    browser = ChromeMock(host=TEST_HOST, port=TEST_PORT)
    await browser.connect()
    chrome_tab = browser.tabs[0]
    yield chrome_tab
    print("gracefully disconnecting chrome tab...")
    try:
        await chrome_tab.disconnect()
    except ConnectionClosed:
        pass 
開發者ID:chuckus,項目名稱:chromewhip,代碼行數:14,代碼來源:test_chrome.py


注:本文中的websockets.exceptions.ConnectionClosed方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。