Constantly monitors if the connection is still open using ping/pong every
`interval` milliseconds. `timeoutCb` is called when the ping/pong doesn't
answer for `pingTimeout` milliseconds. If `pingTimeout` is not set, it
will equal `interval`
18924
function monitor(interval, timeoutCb, pingTimeout) {
  pingTimeout = pingTimeout || interval;
  let currentTimeout;
  let currentInterval;
  let closed = false;

  const onTimeoutExpired = () => {
    if (closed) return;
    closed = true;

    clearTimeout(currentTimeout);
    clearInterval(currentInterval);
    timeoutCb();
  };


  const ping = () => {
    this.ping(undefined, undefined, true);

    if (currentTimeout) return;
    currentTimeout = setTimeout(onTimeoutExpired, pingTimeout);
  };

  this.on('pong', () => {
    clearTimeout(currentTimeout);
    currentTimeout = undefined;
  });

  this.on('close', () => onTimeoutExpired());
  this.on('error', () => onTimeoutExpired());
  currentInterval = setInterval(() => ping(), interval);
}
358842
def ping(self, reconnect=True):
        
        if self._sock is None:
            if reconnect:
                self.connect()
                reconnect = False
            else:
                raise err.Error("Already closed")
        try:
            self._execute_command(COMMAND.COM_PING, "")
            self._read_ok_packet()
        except Exception:
            if reconnect:
                self.connect()
                self.ping(False)
            else:
                raise
854653
def check(conn, command, exit=False, timeout=None, **kw):
    
    command = conn.cmd(command)

    stop_on_error = kw.pop('stop_on_error', True)
    timeout = timeout or conn.global_timeout
    if not kw.get('env'):
        # get the remote environment's env so we can explicitly add
        # the path without wiping out everything
        kw = extend_env(conn, kw)

    conn.logger.info('Running command: %s' % ' '.join(admin_command(conn.sudo, command)))
    result = conn.execute(_remote_check, cmd=command, **kw)
    response = None
    try:
        response = result.receive(timeout)
    except Exception as err:
        # the things we need to do here :(
        # because execnet magic, we cannot catch this as
        # `except TimeoutError`
        if err.__class__.__name__ == 'TimeoutError':
            msg = 'No data was received after %s seconds, disconnecting...' % timeout
            conn.logger.warning(msg)
            # there is no stdout, stderr, or exit code but make the exit code
            # an error condition (non-zero) regardless
            return [], [], -1
        else:
            remote_trace = traceback.format_exc()
            remote_error = RemoteError(remote_trace)
            if remote_error.exception_name == 'RuntimeError':
                conn.logger.error(remote_error.exception_line)
            else:
                for tb_line in remote_trace.split('\n'):
                    conn.logger.error(tb_line)
            if stop_on_error:
                raise RuntimeError(
                    'Failed to execute command: %s' % ' '.join(command)
                )
    if exit:
        conn.exit()
    return response
279358
def join(self, timeout=None):
        
        remaining = timeout

        while self._cb_poll and (remaining is None or remaining > 0):
            now = time.time()
            rv = self._cb_poll.poll(remaining)
            if remaining is not None:
                remaining -= (time.time() - now)

            for command_buffer, event in rv:
                # This command buffer still has pending requests which
                # means we have to send them out first before we can read
                # all the data from it.
                if command_buffer.has_pending_requests:
                    if event == 'close':
                        self._try_reconnect(command_buffer)
                    elif event == 'write':
                        self._send_or_reconnect(command_buffer)

                # The general assumption is that all response is available
                # or this might block.  On reading we do not use async
                # receiving.  This generally works because latency in the
                # network is low and redis is super quick in sending.  It
                # does not make a lot of sense to complicate things here.
                elif event in ('read', 'close'):
                    try:
                        command_buffer.wait_for_responses(self)
                    finally:
                        self._release_command_buffer(command_buffer)

        if self._cb_poll and timeout is not None:
            raise TimeoutError('Did not receive all data in time.')
1238826
def check_port(port, host, timeout=10):
    
    logger.info("trying to open connection to %s:%s", host, port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        logger.info("was connection successful? errno: %s", result)
        if result == 0:
            logger.debug('port is opened: %s:%s' % (host, port))
            return True
        else:
            logger.debug('port is closed: %s:%s' % (host, port))
            return False
    finally:
        sock.close()
996094
async def _pinger(self):
        '''
        

        '''
        async def _do_ping():
            try:
                await pinger_facade.Ping()
                await asyncio.sleep(10, loop=self.loop)
            except CancelledError:
                pass

        pinger_facade = client.PingerFacade.from_connection(self)
        try:
            while True:
                await utils.run_with_interrupt(
                    _do_ping(),
                    self.monitor.close_called,
                    loop=self.loop)
                if self.monitor.close_called.is_set():
                    break
        except websockets.exceptions.ConnectionClosed:
            # The connection has closed - we can't do anything
            # more until the connection is restarted.
            log.debug('ping failed because of closed connection')
            pass
470366
def ping(self, status=None):
        
        newping = not self.ping_watchers
        d = defer.Deferred()
        self.ping_watchers.append(d)
        if newping:
            Ping().ping(self.worker.conn).addBoth(self._pong)

        return d
883013
async def __handle_ping(self, _ : Ping):
        
        self.__last_ping = time.time()
        await ZMQUtils.send(self.__backend_socket, Pong())
983200
def _ping_loop(self):
        
        self.pong_received = True
        self.ping_loop_event.clear()
        while self.state == 'connected':
            if not self.pong_received:
                self.logger.info(
                    'PONG response has not been received, aborting')
                if self.ws:
                    self.ws.close()
                self.queue.put(None)
                break
            self.pong_received = False
            self._send_packet(packet.Packet(packet.PING))
            self.ping_loop_event.wait(timeout=self.ping_interval)
        self.logger.info('Exiting ping task')
76644
def check(self):
        '''  '''
        if self.lastrun + self.interval < time.time():
            return True
        else:
            return False
396793
def monitor(self, timeout):
        

        def check(self, timeout):
            time.sleep(timeout)
            self.stop()
        wather = threading.Thread(target=check)
        wather.setDaemon(True)
        wather.start()
331784
function ping (){
    clearTimeout( ping.timer );
    ping.timer = setTimeout(function(){
      b9.send({ type: 'ping', time: Date.now() });
    }, b9._interval );
  }
141759
async def check_ping_timeout(self):
        
        if self.closed:
            raise exceptions.SocketIsClosedError()
        if time.time() - self.last_ping > self.server.ping_interval + 5:
            self.server.logger.info('%s: Client is gone, closing socket',
                                    self.sid)
            # Passing abort=False here will cause close() to write a
            # CLOSE packet. This has the effect of updating half-open sockets
            # to their correct state of disconnected
            await self.close(wait=False, abort=False)
            return False
        return True
437200
function checkConnection(options, cb) {
    if (count < options.attempts) {
        connectServer(options, callback);
    } else {
        var avg = results.reduce(function(prev, curr) { return prev + curr.time; }, 0);
        var max = results.reduce(function(prev, curr) { return (prev > curr.time) ? prev : curr.time; }, results[0].time);
        var min = results.reduce(function(prev, curr) { return (prev < curr.time) ? prev : curr.time; }, results[0].time);

        avg = avg / results.length;
        var out = {
            address:  options.address,
            port:     options.port,
            attempts: options.attempts,
            avg:      avg,
            max:      max,
            min:      min,
            results:  results
        };

        cb(undefined, out);
    }
}
1210262
function usePing() {
        if (!pingPongStarted) {
            Logger.debug("Starting ping (if configured)")
            pingPongStarted = true;

            if (configuration.heartbeat != undefined) {
                pingInterval = setInterval(sendPing, configuration.heartbeat);
                sendPing();
            }
        }
    }
964540
def _check_connection(self):
        
        # check if connection is expired
        reset = False
        if self._force_recon:
            self.logger.warning(
                "[%s:%s] Error communicating with socket, resetting "
                "connection",
                self.fn or self.host, self.port)
            reset = True

        elif self.heartbeat_controller.is_expired():
            self.logger.warning(
                "[%s:%s] Heartbeat timeout, resetting connection",
                self.fn or self.host, self.port)
            reset = True

        if reset:
            for channel in self._open_channels:
                self.disconnect_channel(channel)
            self._report_connection_status(
                ConnectionStatus(CONNECTION_STATUS_LOST,
                                 NetworkAddress(self.host, self.port)))
            try:
                self.initialize_connection()
            except ChromecastConnectionError:
                self.stop.set()
            return False
        return True
1338980
def heartbeat_timeout(self):
        
        assert not self._closed, "Did we not stop heartbeat_monitor on close?"
        log.error("Heartbeat time out")
        poison_exc = ConnectionLostError('Heartbeat timed out')
        poison_frame = frames.PoisonPillFrame(poison_exc)
        self.dispatcher.dispatch_all(poison_frame)
        # Spec says to just close socket without ConnectionClose handshake.
        self.close()