How to use the websockets.exceptions function in websockets

To help you get started, we’ve selected a few websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oliver-zehentleitner / unicorn-binance-websocket-api / unicorn_binance_websocket_api / unicorn_binance_websocket_api_connection.py View on Github external
elif "Status code not 101: 500" in str(error_msg):
                logging.critical("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                                 str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg))
                self.handler_binance_websocket_api_manager.stream_is_crashing(self.stream_id, str(error_msg))
                sys.exit(1)
            else:
                logging.critical("BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                                 str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg))
                try:
                    self.handler_binance_websocket_api_manager.websocket_list[self.stream_id].close()
                except KeyError:
                    pass
                self.handler_binance_websocket_api_manager.stream_is_crashing(self.stream_id, str(error_msg))
                self.handler_binance_websocket_api_manager.set_restart_request(self.stream_id)
                sys.exit(1)
        except websockets.exceptions.ConnectionClosed as error_msg:
            logging.info("BinanceWebSocketApiSocket->await._conn.__aenter__(" + str(self.stream_id) + ", " +
                         str(self.channels) + ", " + str(self.markets) + ") Exception ConnectionClosed "
                                                                         "Info: " + str(error_msg))
            if "WebSocket connection is closed: code = 1006" in str(error_msg):
                self.handler_binance_websocket_api_manager.websocket_list[self.stream_id].close()
                self.handler_binance_websocket_api_manager.stream_is_crashing(self.stream_id, str(error_msg))
                sys.exit(1)
        return self
github OceanDataTools / openrvdas / logger / writers / cached_data_writer.py View on Github external
logging.info('CachedDataWriter trying to connect to '
                     + self.data_server)
        try:
          async with websockets.connect('ws://' + self.data_server) as ws:
            while True:
              try:
                record = self.send_queue.get_nowait()
                logging.debug('sending record: %s', record)
                record = {'type':'publish', 'data':record}
                await ws.send(json.dumps(record))
                response = await ws.recv()
                logging.debug('received response: %s', response)
              except asyncio.QueueEmpty:
                await asyncio.sleep(.2)

        except websockets.exceptions.ConnectionClosed:
          logging.warning('CachedDataWriter lost websocket connection to '
                          'data server; trying to reconnect.')
          await asyncio.sleep(0.2)

        # If the websocket connection failed
        except OSError as e:
          logging.warning('CachedDataWriter websocket connection to %s '
                          'failed; sleeping before trying again: %s',
                          self.data_server, str(e))
          await asyncio.sleep(5)
github abersheeran / websocks / websocks / client.py View on Github external
assert isinstance(resp, str), "must be str"
                if not json.loads(resp)["ALLOW"]:
                    # websocks close
                    await sock.send(json.dumps({"STATUS": "CLOSED"}))
                    while True:
                        msg = await sock.recv()
                        if isinstance(msg, str):
                            break
                    assert json.loads(msg)["STATUS"] == CLOSED

                    raise WebsocksRefused(
                        f"Websocks server can't connect {host}:{port}"
                    )
            except (AssertionError, KeyError):
                raise WebsocksImplementationError()
            except websockets.exceptions.ConnectionClosedError:
                pass
            else:
                break
        return WebSocket(sock, pool)
github centricular / gstwebrtc-demos / signalling / session-client.py View on Github external
if CALLEE_ID:
                if msg == 'SESSION_OK':
                    await ws.send(send_sdp_ice())
                    sent_sdp = True
                else:
                    print('Unknown reply: {!r}, exiting'.format(msg))
                    return
            else:
                await ws.send(reply_sdp_ice(msg))
                return # Done

print('Our uid is {!r}'.format(PEER_ID))

try:
    asyncio.get_event_loop().run_until_complete(hello())
except websockets.exceptions.InvalidHandshake:
    print('Invalid handshake: are you sure this is a websockets server?\n')
    raise
except ssl.SSLError:
    print('SSL Error: are you sure the server is using TLS?\n')
    raise
github abersheeran / websocks / websocks / _websocks.py View on Github external
async def send(self, data: bytes) -> int:
        try:
            await self.sock.send(data)
        except websockets.exceptions.ConnectionClosed:
            raise ConnectionResetError("websocket closed.")
        logger.debug(f">>> {data}")
        return len(data)
github appditto / pippin_nano_wallet / pippin / network / nano_websocket.py View on Github external
async def loop(self):
        while not self.stop:
            try:
                rec = json.loads(await self.ws.recv())
                topic = rec.get("topic", None)
                if topic and topic == "confirmation":
                    await self.arrival_cb(rec["message"])
                elif topic and topic == "active_difficulty":
                    if "network_current" in rec["message"]:
                        WorkClient.instance().active_difficulty = rec["message"]["network_current"]
            except KeyboardInterrupt:
                break
            except websockets.exceptions.ConnectionClosed as e:
                log.server_logger.error(f"NANO WS: Connection closed to websocket. Code: {e.code} , reason: {e.reason}.")
                await self.reconnect_forever()
            except Exception as e:
                log.server_logger.critical(f"NANO WS: Unknown exception while handling getting a websocket message:\n{traceback.format_exc()}")
                await self.reconnect_forever()
github machinezone / cobra / cobras / server / app.py View on Github external
key = state.connection_id
    app['connections'][key] = (state, websocket)

    app['stats'].incrConnections(appkey)
    connectionCount = len(app['connections'])
    state.log(f'(open) connections {connectionCount}')

    try:
        async for message in websocket:
            msgCount += 1
            await processCobraMessage(state, websocket, app, message)
            if not state.ok:
                raise Exception(state.error)

    except websockets.exceptions.ProtocolError as e:
        print(e)
        state.log('Protocol error')
    except websockets.exceptions.ConnectionClosedOK:
        state.log('Connection closed properly')
    except websockets.exceptions.ConnectionClosedError:
        state.log('Connection closed with an error')
    except Exception as e:
        print(e)
        print('Generic Exception caught in {}'.format(traceback.format_exc()))
    finally:
        del app['connections'][key]

        subCount = len(state.subscriptions)

        if subCount > 0:
            state.log('cancelling #{} subscriptions'.format(subCount))
github phiresky / backchannel-prediction / web_vis / py / server.py View on Github external
elif msg['type'] == "getConversations":
                        await websocket.send(json.dumps({"id": id, "data": conversations}))
                    elif msg['type'] == "getFeature":
                        conv = sanitize_conversation(msg['conversation'])
                        await sendFeature(websocket, id, conv, msg['feature'], microphone_handler)
                    elif msg['type'] == "echo":
                        await websocket.send(json.dumps({"id": id}))
                    else:
                        raise Exception("Unknown msg " + json.dumps(msg))
                except Exception as e:
                    if isinstance(e, websockets.exceptions.ConnectionClosed): raise e
                    import traceback
                    await websocket.send(json.dumps({"id": id, "error": traceback.format_exc()}))
                    print(traceback.format_exc())

        except websockets.exceptions.ConnectionClosed as e:
            return
github rev3ks / Crypto-Liquid-Market-Maker / trader / socket / manager.py View on Github external
def run(self):
    if self.auth:
      self.auth_stamp()
    self.run = True
    loop = asyncio.get_event_loop()
    while self.run:
      try:
        loop.run_until_complete(self.connect())

      except asyncio.TimeoutError:
        logger.warning("Ping Timeout, Restarting Web Socket")

      except websockets.exceptions.ConnectionClosed:
        logger.warning("Connection Closed, Restarting Web Socket")

      except KeyboardInterrupt:
        logger.error("Keyboard Interruption, stopping socket")
        raise

      except Exception:
        logger.error("last message received {} seconds ago/n{}"
                     .format(self.last_time_watch(),
                             traceback.format_exc()))
        logger.warning("Restarting Web Socket")