Performs a keepalive to avoid idle disconnect
967261
def _keepalive(self):
        
        try:
            keptalive = False
            if self._customkeepalives:
                kaids = list(self._customkeepalives.keys())
                for keepalive in kaids:
                    try:
                        cmd, callback = self._customkeepalives[keepalive]
                    except TypeError:
                        # raw_command made customkeepalives None
                        break
                    except KeyError:
                        # raw command ultimately caused a keepalive to
                        # deregister
                        continue
                    if callable(cmd):
                        cmd()
                        continue
                    keptalive = True
                    cmd['callback'] = self._keepalive_wrapper(callback)
                    self.raw_command(**cmd)
            if not keptalive:
                if self.incommand:
                    # if currently in command, no cause to keepalive
                    return
                self.raw_command(netfn=6, command=1,
                                 callback=self._keepalive_wrapper(None))
        except exc.IpmiException:
            self._mark_broken()
1175774
private void keepAlive(boolean retryOnFailure) {
    long sessionId = state.getSessionId();

    // If the current sessions state is unstable, reset the connection before sending a keep-alive.
    if (state.getState() == Session.State.UNSTABLE)
      connection.reset();

    KeepAliveRequest request = KeepAliveRequest.builder()
      .withSession(sessionId)
      .withCommandSequence(state.getCommandResponse())
      .withEventIndex(state.getEventIndex())
      .build();

    state.getLogger().trace("{} - Sending {}", sessionId, request);
    connection.<KeepAliveRequest, KeepAliveResponse>sendAndReceive(request).whenComplete((response, error) -> {
      if (state.getState() != Session.State.CLOSED) {
        if (error == null) {
          state.getLogger().trace("{} - Received {}", sessionId, response);
          // If the request was successful, update the address selector and schedule the next keep-alive.
          if (response.status() == Response.Status.OK) {
            connection.reset(response.leader(), response.members());
            state.setState(Session.State.OPEN);
            scheduleKeepAlive();
          }
          // If the session is unknown, immediate expire the session.
          else if (response.error() == CopycatError.Type.UNKNOWN_SESSION_ERROR) {
            state.setState(Session.State.EXPIRED);
          }
          // If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
          // This will ensure that the address selector selects all servers without filtering on the leader.
          else if (retryOnFailure && connection.leader() != null) {
            connection.reset(null, connection.servers());
            keepAlive(false);
          }
          // If no leader was set, set the session state to unstable and schedule another keep-alive.
          else {
            state.setState(Session.State.UNSTABLE);
            scheduleKeepAlive();
          }
        }
        // If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
        // This will ensure that the address selector selects all servers without filtering on the leader.
        else if (retryOnFailure && connection.leader() != null) {
          connection.reset(null, connection.servers());
          keepAlive(false);
        }
        // If no leader was set, set the session state to unstable and schedule another keep-alive.
        else {
          state.setState(Session.State.UNSTABLE);
          scheduleKeepAlive();
        }
      }
    });
  }
18090
function() {
        clearInterval(this._checkConnectionTimer);
        this._checkConnectionTimer = undefined;
        this.muc.joinedRooms = {};
        this._isLogout = true;
        this.helpers.setUserCurrentJid('');

        if (Utils.getEnv().browser) {
            this.connection.flush();
            this.connection.disconnect();
        } else {
            this.Client.end();
        }
    }
311050
def _connected(self, watcher, events):
        """"""
        self.connected = True
        self._finish()
        self.deferred.callback(self.sock)
391053
def timeout_keep_alive_handler(self):
        
        if not self.transport.is_closing():
            event = h11.ConnectionClosed()
            self.conn.send(event)
            self.transport.close()
231318
private void createAndWriteKeepAlive(final ChannelHandlerContext ctx) {
        final CouchbaseRequest keepAlive = createKeepAliveRequest();
        if (keepAlive != null) {
            Subscriber<CouchbaseResponse> subscriber = new KeepAliveResponseAction(ctx);
            keepAlive.subscriber(subscriber);
            keepAlive
                .observable()
                .timeout(env().keepAliveTimeout(), TimeUnit.MILLISECONDS)
                .subscribe(subscriber);

            onKeepAliveFired(ctx, keepAlive);

            Channel channel = ctx.channel();
            if (channel.isActive() && channel.isWritable()) {
                ctx.pipeline().writeAndFlush(keepAlive);
            }
        }
    }
1054655
private boolean enableKeepalive(PollController conn,
                                  boolean isNew)
      throws IOException
  {
    
    if (_selectMax <= _connectionCount.get()) {
      throw new IllegalStateException(this + " keepalive overflow "
                                      + _connectionCount + " max=" + _selectMax);

      /*
      conn.requestDestroy();

      return false;
      */
    }

    JniSocketImpl socket = (JniSocketImpl) conn.getSocket();

    if (socket == null) {
      throw new IllegalStateException(this + " socket empty for " + conn);
    }

    int nativeFd = socket.getNativeFd();

    if (nativeFd < 0) {
      throw new IllegalStateException(this + " attempted keepalive with closed file descriptor fd=" + nativeFd
                                      + "\n " + socket
                                      + "\n " + conn);
    }
    else if (_connections.length() <= nativeFd) {
      throw new IllegalStateException(this + " select overflow for file descriptor fd=" + nativeFd + " " + conn);
    }

    if (! _lifecycle.isActive()) {
      throw new IllegalStateException("inactive keepalive");
    }

    if (isNew) {
      setMaxConnection(nativeFd);

      _connections.set(nativeFd, conn);

      _connectionCount.incrementAndGet();
    }

    int result = addNative(_fd, nativeFd, isNew);

    // result < 0 would likely be a disconnect

    return result == 0;
  }
505106
function onDisconnect() {
	var rids = Object.keys( cache ),
		len = rids.length,
		i;

	// TODO: log
	console.log( process.pid, 'disconnected' );

	// Abort any pending requests...
	for ( i = 0; i < len; i++ ) {
		cache[ rids[i] ].abort();

		// TODO: log
		console.log( process.pid, 'aborting request: ', rids[ i ] );
	}
}
972517
def maintainConnections(self, force=False):
        
        now = time.perf_counter()
        if now < self.nextCheck and not force:
            return False
        self.nextCheck = now + (self.config.RETRY_TIMEOUT_NOT_RESTRICTED
                                if self.isKeySharing
                                else self.config.RETRY_TIMEOUT_RESTRICTED)
        missing = self.connectToMissing()
        self.retryDisconnected(exclude=missing)
        logger.trace("{} next check for retries in {:.2f} seconds"
                     .format(self, self.nextCheck - now))
        return True
513068
public function keepaliveProbe() {
        if($this->keepalive_interval <=0 || $this->keepalive_timeout <=0){
            return ;
        }
        
        $this->keepalive_timer = Yii::$app->eventLooper->addInterval($this->keepalive_interval*1000, function($timerId, $interval, $flag, $args=null){
            $now = microtime(true);
            Yii::debug(" ...", 'beyod');
            foreach($this->connections as $id =>$conn){
                if($conn->request_at >0 && $conn->request_at < ($now - $this->keepalive_timeout)){
                    Yii::debug($conn." keepalive timed out,close it",'beyod');
                    $conn->close();
                }
            }
        });
    }
12302
def keep_alive(self, val: bool) -> None:
        
        self._keepalive = val
        if self._keepalive_handle:
            self._keepalive_handle.cancel()
            self._keepalive_handle = None
532108
function usePersistentConnection()
    {
        if (isset($this->outgoing_headers['Accept-Encoding'])) {
            return FALSE;
        }
        $this->protocol_version     = '1.1';
        $this->persistentConnection = TRUE;
        $this->setHeader('Connection', 'Keep-Alive');

        return TRUE;
    }
1067281
private void scheduleKeepAlive() {
    if (keepAlive != null)
      keepAlive.cancel();
    keepAlive = context.schedule(interval, () -> {
      keepAlive = null;
      if (state.getState().active()) {
        keepAlive();
      }
    });
  }
539489
public function keepAlive()
    {
        $loop = \React\EventLoop\Factory::create();
        $loop->addPeriodicTimer(30, function () {
            $listenKey = $this->listenKey;
            $this->httpRequest("v1/userDataStream?listenKey={$listenKey}", "PUT", []);
        });
        $loop->run();
    }
632103
def keep_alive_timeout_callback(self):
        
        time_elapsed = time() - self._last_response_time
        if time_elapsed < self.keep_alive_timeout:
            time_left = self.keep_alive_timeout - time_elapsed
            self._keep_alive_timeout_handler = self.loop.call_later(
                time_left, self.keep_alive_timeout_callback
            )
        else:
            logger.debug("KeepAlive Timeout. Closing connection.")
            self.transport.close()
            self.transport = None
1365737
function () {
        var data = this._conn._data;

        // if no requests are in progress, poll
        if (this._conn.authenticated && this._requests.length === 0 &&
            data.length === 0 && !this._conn.disconnecting) {
            Strophe.info("no requests during idle cycle, sending " +
                         "blank request");
            data.push(null);
        }

        if (this._conn.paused) {
            return;
        }

        if (this._requests.length < 2 && data.length > 0) {
            var body = this._buildBody();
            for (var i = 0; i < data.length; i++) {
                if (data[i] !== null) {
                    if (data[i] === "restart") {
                        body.attrs({
                            to: this._conn.domain,
                            "xml:lang": "en",
                            "xmpp:restart": "true",
                            "xmlns:xmpp": Strophe.NS.BOSH
                        });
                    } else {
                        body.cnode(data[i]).up();
                    }
                }
            }
            delete this._conn._data;
            this._conn._data = [];
            this._requests.push(
                new Strophe.Request(body.tree(),
                                    this._onRequestStateChange.bind(
                                        this, this._conn._dataRecv.bind(this._conn)),
                                    body.tree().getAttribute("rid")));
            this._throttledRequestHandler();
        }

        if (this._requests.length > 0) {
            var time_elapsed = this._requests[0].age();
            if (this._requests[0].dead !== null) {
                if (this._requests[0].timeDead() >
                    Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
                    this._throttledRequestHandler();
                }
            }

            if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
                Strophe.warn("Request " +
                             this._requests[0].id +
                             " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
                             " seconds since last activity");
                this._throttledRequestHandler();
            }
        }
    }
1338598
def steady_connection(self):
        """"""
        return connect(
            self._creator, self._maxusage, self._setsession,
            self._failures, self._ping, self._closeable,
            *self._args, **self._kwargs)