Set TCP keepalive on an open socket.

    It activates after 1 second (after_idle_sec) of idleness,
    then sends a keepalive ping once every 3 seconds (interval_sec),
    and closes the connection after 5 failed ping (max_fails), or 15 seconds
19567
def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
    
    if hasattr(socket, "SO_KEEPALIVE"):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    if hasattr(socket, "TCP_KEEPIDLE"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
    if hasattr(socket, "TCP_KEEPINTVL"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
    if hasattr(socket, "TCP_KEEPCNT"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
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
116749
def _do_tcp_check(self, ip, results):
        
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            sock.connect((ip, self.conf['tcp_check_port']))
        except:
            # Any problem during the connection attempt? We won't diagnose it,
            # we just indicate failure by adding the IP to the list
            results.append(ip)
        finally:
            sock.close()
1289083
def _Start_refresh_timer(self):
		
		if self._refreshPeriod > 60:
			interval = self._refreshPeriod - 60
		else:
			interval = 60
		self._refreshTimer = Timer(self._refreshPeriod, self.Refresh)
		# TODO:handle exit and logout active connections. revert from daemon then
		self._refreshTimer.setDaemon(True)
		self._refreshTimer.start()
170921
function() {
        try {
          if (socket && socket.readyState == 1) {
            return;
          }

          socket = new WebSocket(address, []);

          socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
          socketRealTimeStatusInterval = setInterval(function() {
            switch (socket.readyState) {
              case 2:
                onCloseHandler(null);
                break;
              case 3:
                socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
                break;
            }
          }, 5000);

          socket.onopen = function(event) {
            waitForSocketToConnect(function() {
              eventCallback["open"]();
            });
          }

          socket.onmessage = function(event) {
            var messageData = JSON.parse(event.data);
            eventCallback["message"](messageData);

            /**
             * To avoid manually closing socket's connection
             */
            forceCloseSocket = false;

            socketCloseTimeout && clearTimeout(socketCloseTimeout);
            forceCloseTimeout && clearTimeout(forceCloseTimeout);

            socketCloseTimeout = setTimeout(function() {
              /**
               * If message's type is not 5, socket won't get any acknowledge packet,therefore
               * you may think that connection has been closed and you would force socket
               * to close, but before that you should make sure that connection is actually closed!
               * for that, you must send a ping message and if that message don't get any
               * responses too, you are allowed to manually kill socket connection.
               */
              ping();

              /**
               * We set forceCloseSocket as true so that if your ping's response don't make it
               * you close your socket
               */
              forceCloseSocket = true;

              /**
               * If type of messages are not 5, you won't get ant ACK packets
               * for that being said, we send a ping message to be sure of
               * socket connection's state. The ping message should have an
               * ACK, if not, you're allowed to close your socket after
               * 4 * [connectionCheckTimeout] seconds
               */
              forceCloseTimeout = setTimeout(function() {
                if (forceCloseSocket) {
                  socket.close();
                }
              }, connectionCheckTimeout);

            }, connectionCheckTimeout * 1.5);
          }

          socket.onclose = function(event) {
            onCloseHandler(event);
          }

          socket.onerror = function(event) {
            eventCallback["error"](event);
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4000,
            errorMessage: "ERROR in WEBSOCKET!",
            errorEvent: error
          });
        }
      }
598799
function() {
    
        that.connected = true;
        that.tcp_connection.setKeepAlive( true );	
        
        if ( that.message_buffer.length ) {
            while( that.message_buffer.length ) {
                that.tcp_connection.write( that.message_buffer.shift() );
            }
        }
    }
891549
function keepAlive(k) {
	if (k) {
		if (++keepAliveIntervalCount === 1) {
			// The actual duration doesn't really matter: it should be large but not too large.
			keepAliveIntervalId = setInterval(() => { }, 24 * 60 * 60 * 1000);
		}
	} else {
		if (--keepAliveIntervalCount === 0) {
			clearInterval(keepAliveIntervalId);
		}
	}
	debug(`keepAlive(${k}) => ${keepAliveIntervalCount}`);
}
1156149
def wait_for_socket
      return unless Jets.rack?

      retries = 0
      max_retries = 30 # 15 seconds at a delay of 0.5s
      delay = 0.5
      if ENV['C9_USER'] # overrides for local testing
        max_retries = 3
        delay = 3
      end
      begin
        server = TCPSocket.new('localhost', 9292)
        server.close
      rescue Errno::ECONNREFUSED
        puts "Unable to connect to localhost:9292. Delay for #{delay} and will try to connect again."  if ENV['JETS_DEBUG']
        sleep(delay)
        retries += 1
        if retries < max_retries
          retry
        else
          puts "Giving up on trying to connect to localhost:9292"
          return false
        end
      end
      puts "Connected to localhost:9292 successfully"
      true
    end
960722
private function should_send_keepalive_update( $use_network_level_storage = null ) {
            $keepalive_timestamp = $this->_storage->get( 'keepalive_timestamp', 0, $use_network_level_storage );

            if ( $keepalive_timestamp < ( time() - WP_FS__TIME_WEEK_IN_SEC ) ) {
                // If updated more than 7 days ago, trigger a keepalive and update the time it was triggered.
                return true;
            } else {
                // If updated 7 days ago or less, "flip a coin", if the value is 7 trigger a keepalive and update the last time it was triggered.
                return ( 7 == rand( 1, 7 ) );
            }
        }
279795
def wait(self):
        
        if self.error:
            raise self.error
        if not self.running:
            raise ValueError("Unable to send until client has been started.")
        try:
            self._handler.wait()
        except (errors.TokenExpired, errors.AuthenticationException):
            log.info("Sender disconnected due to token error. Attempting reconnect.")
            self.reconnect()
        except (errors.LinkDetach, errors.ConnectionClose) as shutdown:
            if shutdown.action.retry and self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except errors.MessageHandlerError as shutdown:
            if self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except Exception as e:
            log.info("Unexpected error occurred (%r).", e)
            raise EventHubError("Send failed: {}".format(e))
1341107
@Override
  public NettyChannelBuilder keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) {
    checkArgument(keepAliveTimeout > 0L, "keepalive timeout must be positive");
    keepAliveTimeoutNanos = timeUnit.toNanos(keepAliveTimeout);
    keepAliveTimeoutNanos = KeepAliveManager.clampKeepAliveTimeoutInNanos(keepAliveTimeoutNanos);
    return this;
  }
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
152401
def on_open(self, ws):
        """"""
        def keep_alive(interval):
            while True:
                time.sleep(interval)
                self.ping()

        start_new_thread(keep_alive, (self.keep_alive_interval, ))
254031
def _monitor(last_ping, stop_plugin, is_shutting_down, timeout=5):
    
    _timeout_count = 0
    _last_check = time.time()
    _sleep_interval = 1
    # set _sleep_interval if less than the timeout
    if timeout < _sleep_interval:
        _sleep_interval = timeout
    while True:
        time.sleep(_sleep_interval)
        # Signals that stop_plugin has been called
        if is_shutting_down():
            return
        # have we missed a ping during the last timeout duration
        if ((time.time() - _last_check) > timeout) and ((time.time() - last_ping()) > timeout):
            # reset last_check
            _last_check = time.time()
            _timeout_count += 1
            LOG.warning("Missed ping health check from the framework. " +
                        "({} of 3)".format(_timeout_count))
            if _timeout_count >= 3:
                stop_plugin()
                return
        elif (time.time() - last_ping()) <= timeout:
            _timeout_count = 0
569998
def http_keepalive (headers):
    
    keepalive = headers.get("Keep-Alive")
    if keepalive is not None:
        try:
            keepalive = int(keepalive[8:].strip())
        except (ValueError, OverflowError):
            keepalive = DEFAULT_KEEPALIVE
    else:
        keepalive = DEFAULT_KEEPALIVE
    return keepalive
171136
def start_client(host, port):
    '''  '''
    pydev_log.info("Connecting to %s:%s", host, port)

    s = socket(AF_INET, SOCK_STREAM)

    #  Set TCP keepalive on an open socket.
    #  It activates after 1 second (TCP_KEEPIDLE,) of idleness,
    #  then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
    #  and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
    try:
        from socket import IPPROTO_TCP, SO_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
        s.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
        s.setsockopt(IPPROTO_TCP, TCP_KEEPIDLE, 1)
        s.setsockopt(IPPROTO_TCP, TCP_KEEPINTVL, 3)
        s.setsockopt(IPPROTO_TCP, TCP_KEEPCNT, 5)
    except ImportError:
        pass  # May not be available everywhere.

    try:
        # 10 seconds default timeout
        timeout = int(os.environ.get('PYDEVD_CONNECT_TIMEOUT', 10))
        s.settimeout(timeout)
        s.connect((host, port))
        s.settimeout(None)  # no timeout after connected
        pydev_log.info("Connected.")
        return s
    except:
        pydev_log.exception("Could not connect to %s: %s", host, port)
        raise
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;
  }