How to use the websockets.exceptions.ConnectionClosed 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 OceanDataTools / openrvdas / gui / display_server.py View on Github external
# Now that we've gotten all the back results, create a single
    # DatabaseFieldReader to read all the fields.
    reader = DatabaseFieldReader(fields,
                                 self.database, self.database_host,
                                 self.database_user, self.database_password)
    while True:
      # If we do have results, package them up and send them
      if results:
        send_message = json_dumps(results)
        logging.info('sending: %s', send_message)
        try:
          await websocket.send(send_message)

        # If the client has disconnected, we're done here - go home
        except websockets.exceptions.ConnectionClosed:
          self.unregister_fields(fields)
          return

      # New results or not, take a nap before trying to fetch more results
      logging.debug('Sleeping %g seconds', self.interval)
      await asyncio.sleep(self.interval)

      # What's the timestamp of the most recent result we've seen?
      # Each value should be a list of (timestamp, value) pairs. Look
      # at the last timestamp in each value list.
      for field in results:
        last_timestamp = results[field][-1][0]
        max_timestamp_seen = max(max_timestamp_seen, last_timestamp)
      logging.debug('Results: %s', results)
      logging.info('Received %d fields, max timestamp %f',
                   len(results), max_timestamp_seen)
github jjuraska / cruzhacks2018 / client.py View on Github external
# assemble the header for the speech.config message
        msg = 'Path: telemetry\r\n'
        msg += 'Content-Type: application/json; charset=utf-8\r\n'
        msg += 'X-RequestId: ' + self.request_id + '\r\n'
        msg += 'X-Timestamp: ' + utils.generate_timestamp() + '\r\n'
        # append the body of the message
        msg += '\r\n' + json.dumps(payload, indent=2)

        # DEBUG PRINT
        # print('>>', msg)
        # sys.stdout.flush()

        try:
            await self.ws.send(msg)
        except websockets.exceptions.ConnectionClosed as e:
            print('Connection closed: {0}'.format(e))
            return
github beveradb / pysonofflan / pysonofflan / sonoffdevice.py View on Github external
try:
            self.logger.debug('setup_connection yielding to connect()')
            await self.client.connect()
            self.logger.debug(
                'setup_connection yielding to send_online_message()')
            await self.client.send_online_message()
            self.logger.debug(
                'setup_connection yielding to receive_message_loop()')
            await self.client.receive_message_loop()
        except websockets.InvalidMessage as ex:
            self.logger.error('Unable to connect: %s' % ex)
            self.shutdown_event_loop()
        except ConnectionRefusedError:
            self.logger.error('Unable to connect: connection refused')
            self.shutdown_event_loop()
        except websockets.exceptions.ConnectionClosed:
            self.logger.error('Connection closed unexpectedly')
            self.shutdown_event_loop()
        finally:
            self.logger.debug(
                'finally: closing websocket from setup_connection')
            await self.client.close_connection()

        self.logger.debug('setup_connection resumed, exiting')
github beerfactory / hbmqtt / hbmqtt / adapters.py View on Github external
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)
github dgomes / iia-ia-bomberman / server.py View on Github external
if path == "/viewer":
                        logger.info("Viewer connected")
                        self.viewers.add(websocket)
                        if self.game.running:
                            game_info = self.game.info()
                            game_info["highscores"] = self._highscores
                            await websocket.send(json.dumps(game_info))

                if data["cmd"] == "key" and self.current_player.ws == websocket:
                    logger.debug((self.current_player.name, data))
                    if len(data["key"]):
                        self.game.keypress(data["key"][0])
                    else:
                        self.game.keypress("")

        except websockets.exceptions.ConnectionClosed as c:
            logger.info(f"Client disconnected: {c}")
            if websocket in self.viewers:
                self.viewers.remove(websocket)
github abersheeran / websocks / server.py View on Github external
async def recv(self, num: int = 0):
        try:
            data = await self.sock.recv()
        except websockets.exceptions.ConnectionClosed:
            raise ConnectionResetError('Websocket closed.')
        logger.debug(f"<<< {data}")
        return data
github CoinAlpha / hummingbot / hummingbot / market / ddex / ddex_api_order_book_data_source.py View on Github external
# 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()
github sjdv1982 / seamless / seamless / communion_server.py View on Github external
#print("LISTEN")
        self.peers[websocket] = peer_config
        self.message_count[websocket] = 1000 if incoming else 0
        self.futures[websocket] = {}
        communion_client_manager.add_servant(
            websocket,
            peer_config["id"],
            config_servant=peer_config["servant"],
            config_master=self.config_master 
        )

        try:
            while 1:
                message = await websocket.recv()
                asyncio.ensure_future(self._process_message_from_peer(websocket, message))
        except (websockets.exceptions.ConnectionClosed, ConnectionResetError):
            pass
        except Exception:
            traceback.print_exc()
        finally:
            self.peers.pop(websocket)
            self.message_count.pop(websocket)
            self.futures.pop(websocket)
            communion_client_manager.remove_servant(websocket)
github norrisng / FcomServer / bot / discord_bot.py View on Github external
logging.error("Couldn't login (discord.errors.HTTPException)")
            logging.error(f'{e.message}')

            if wait_interval < max_wait_interval:
                wait_interval = wait_interval + 5
            asyncio.sleep(wait_interval)

        except ClientError as e:
            logging.error("Couldn't login (discord.errors.ClientError)")
            logging.error(f'{e.message}')

            if wait_interval < max_wait_interval:
                wait_interval = wait_interval + 5
            asyncio.sleep(wait_interval)

        except websocket_error.ConnectionClosed as e:
            logger.info(f'{e.message}')

            # Don't reconnect on authentication failure
            if e.code == 4004:
                logging.error("Authentication error!")
                retry = False
                raise

        else:
            break