Check the status of a remote port.

@param sHostName
Hostname or IP address to check.
@param nPort
Port number to check.
@param nTimeoutMillisecs
Connection timeout in milliseconds.
@return Never <code>null</code>.
328319
@Nonnull
  public static ENetworkPortStatus checkPortOpen (@Nonnull @Nonempty final String sHostName,
                                                  @Nonnegative final int nPort,
                                                  @Nonnegative final int nTimeoutMillisecs)
  {
    ValueEnforcer.notEmpty (sHostName, "Hostname");
    ValueEnforcer.isGE0 (nPort, "Port");
    ValueEnforcer.isGE0 (nTimeoutMillisecs, "TimeoutMillisecs");

    LOGGER.info ("Checking TCP port status for " +
                 sHostName +
                 ":" +
                 nPort +
                 " with timeouf of " +
                 nTimeoutMillisecs +
                 " ms");

    try (final Socket aSocket = new Socket ())
    {
      aSocket.setReuseAddress (true);
      final SocketAddress aSocketAddr = new InetSocketAddress (sHostName, nPort);
      aSocket.connect (aSocketAddr, nTimeoutMillisecs);
      return ENetworkPortStatus.PORT_IS_OPEN;
    }
    catch (final IOException ex)
    {
      // Can also be:
      // Connection refused: connect
      if (ex.getMessage ().startsWith ("Connection refused"))
        return ENetworkPortStatus.PORT_IS_CLOSED;
      if (ex instanceof java.net.UnknownHostException)
        return ENetworkPortStatus.HOST_NOT_EXISTING;
      if (ex instanceof java.net.SocketTimeoutException)
        return ENetworkPortStatus.CONNECTION_TIMEOUT;
      if (ex instanceof java.net.ConnectException)
      {
        // E.g. for port 0
        return ENetworkPortStatus.GENERIC_IO_ERROR;
      }
      LOGGER.error ("Other error checking TCP port status", ex);
      return ENetworkPortStatus.GENERIC_IO_ERROR;
    }
  }
1204729
@Nonnull
  public EChange setConnectionTimeoutMilliSecs (final long nMilliSecs)
  {
    if (m_nConnectionTimeoutMilliSecs == nMilliSecs)
      return EChange.UNCHANGED;
    m_nConnectionTimeoutMilliSecs = nMilliSecs;
    return EChange.CHANGED;
  }
273570
private static int getHttpTimeout(Storage st) {
    if (!(st instanceof NNStorage))
      return DFS_IMAGE_TRANSFER_TIMEOUT_DEFAULT; 
    NNStorage storage = (NNStorage) st;
    if (storage == null || storage.getConf() == null) {
      return DFS_IMAGE_TRANSFER_TIMEOUT_DEFAULT;
    }
    return storage.getConf().getInt(DFS_IMAGE_TRANSFER_TIMEOUT_KEY,
        DFS_IMAGE_TRANSFER_TIMEOUT_DEFAULT);
  }
163194
@Override
    protected void checkForTimeouts() {
        // See if anything may have timed out
        if (currentTime < nextTimeoutTime) {
            return;
        }
        Set<SelectionKey> selectorKeys = selector.keys();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "checkForTimeouts - checking " + selectorKeys.size() + " keys for timeouts");
        }
        if (selectorKeys.isEmpty()) {
            // if this isn't the primary (first) selector, see if it should be closed
            if (countIndex != 0) {
                // if we have already been waiting, and still no keys, and this isn't
                // the primary
                // selector, we should close this selector/thread
                if (waitingToQuit) {
                    quit = true;
                } else {
                    wqm.updateCount(countIndex, WorkQueueManager.CS_DELETE_IN_PROGRESS, channelType);
                    waitingToQuit = true;
                    nextTimeoutTime = currentTime + TCPFactoryConfiguration.getChannelSelectorWaitToTerminate();

                }
            } else {
                nextTimeoutTime = currentTime + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();
            }
        } else {
            waitingToQuit = false;
            // go through requests, timing out those that need it, and calculating new
            // timeout
            // set nexttimeouttime to whatever the selectoridletimeout is, and work
            // back from there
            nextTimeoutTime = currentTime + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();

            for (SelectionKey key : selectorKeys) {
                try {
                    if (0 == key.interestOps()) {
                        // not active
                        continue;
                    }
                    // only consider keys that are currently waiting for connect
                    ConnectInfo ci = (ConnectInfo) key.attachment();

                    if (ci.timeout != TCPConnectRequestContext.NO_TIMEOUT) {
                        if (ci.nextTimeoutTime <= currentTime) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                                Tr.event(this, tc, "Inactivity timeout on connect operation for channel" + ci.ioSocket.getChannel());
                            }

                            // create timeout exception to pass to callback error method
                            // Add local and remote address information
                            InetSocketAddress iaRemote = ci.remoteAddress;
                            InetSocketAddress iaLocal = ci.localAddress;
                            IOException e = new SocketTimeoutException("Socket operation timed out before it could be completed. local=" + iaLocal + " remote=" + iaRemote);

                            // Hand off to another thread
                            ci.setError(e);
                            if (wqm.dispatchConnect(ci)) {
                                // unable to dispatch error, handle now
                                key.cancel();
                                ci.ioSocket.close();
                            }
                        } else {
                            // see if we should timeout sooner than our current setting
                            if (ci.nextTimeoutTime < nextTimeoutTime) {
                                nextTimeoutTime = ci.nextTimeoutTime;
                            }
                        }
                    }
                } catch (CancelledKeyException cke) {
                    // either we didn't get the key, or we already dispatched the
                    // error. In either case, there is nothing more to do
                    continue;
                }
            }
        }
    }
942911
public HttpConnection getConnectionWithTimeout(
        final HostConfiguration hostConfiguration, final long timeout) {

        final ConnectionInfo ci = getConnectionInfo();
        HttpConnection httpConnection = ci.conn;

        // make sure the host and proxy are correct for this connection
        // close it and set the values if they are not
        if(httpConnection == null || !finishLastResponse(httpConnection)
            || !hostConfiguration.hostEquals(httpConnection)
            || !hostConfiguration.proxyEquals(httpConnection)) {

            if(httpConnection != null && httpConnection.isOpen()) {
                closer.closeConnection(httpConnection);
            }

            httpConnection = new HttpConnection(hostConfiguration);
            httpConnection.setHttpConnectionManager(this);
            httpConnection.getParams().setDefaults(this.params);
            ci.conn = httpConnection;

            httpConnection.setHost(hostConfiguration.getHost());
            httpConnection.setPort(hostConfiguration.getPort());
            httpConnection.setProtocol(hostConfiguration.getProtocol());
            httpConnection.setLocalAddress(hostConfiguration.getLocalAddress());

            httpConnection.setProxyHost(hostConfiguration.getProxyHost());
            httpConnection.setProxyPort(hostConfiguration.getProxyPort());
        }

        // remove the connection from the timeout handler
        ci.idleStartTime = Long.MAX_VALUE;

        return httpConnection;
    }
230308
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        if (portName == null) {
            return getPort(serviceEndpointInterface);
        }
        java.lang.String inputPortName = portName.getLocalPart();
        if ("NetworkServiceInterfacePort".equals(inputPortName)) {
            return getNetworkServiceInterfacePort();
        }
        else  {
            java.rmi.Remote _stub = getPort(serviceEndpointInterface);
            ((org.apache.axis.client.Stub) _stub).setPortName(portName);
            return _stub;
        }
    }
158382
function TChannelPeer(channel, hostPort, options) {
    assert(hostPort !== '0.0.0.0:0', 'Cannot create ephemeral peer');

    options = options || {};
    EventEmitter.call(this);

    this.stateChangedEvent = this.defineEvent('stateChanged');
    this.allocConnectionEvent = this.defineEvent('allocConnection');
    this.removeConnectionEvent = this.defineEvent('removeConnection');
    this.deltaOutConnectionEvent = this.defineEvent('deltaOutConnection');

    this.channel = channel;
    this.socketInitTimeout = channel.initTimeout;
    this.logger = this.channel.logger;
    this.timers = this.channel.timers;
    this.random = this.channel.random;
    this.hostPort = hostPort;
    this.connections = [];
    this.pendingIdentified = 0;
    this.heapElements = [];
    this.scoreStrategy = null;
    this.draining = null;
    this.boundOnIdentified = onIdentified;
    this.boundOnConnectionError = onConnectionError;
    this.boundOnConnectionClose = onConnectionClose;
    this.boundOnPendingChange = onPendingChange;
    this.scoreRange = null;

    // Timestamp when next conn attempt is allowed
    this.nextConnAttemptTime = 0;
    // How long to delay conn attempt by on failure (ms)
    this.nextConnAttemptDelay = 0;
    // Whether we are doing a connection attempt
    this.hasConnectionAttempt = false;

    this.waitForIdentifiedListeners = [];

    this.reportInterval = options.reportInterval || DEFAULT_REPORT_INTERVAL;
    if (this.reportInterval > 0 && this.channel.emitConnectionMetrics) {
        this.reportTimer = this.timers.setTimeout(
            onReport, this.reportInterval
        );
    }

    this.connectionAttemptDelay = this.channel.connectionAttemptDelay ||
        INITIAL_CONN_ATTEMPT_DELAY;
    this.maxConnectionAttemptDelay = this.channel.maxConnectionAttemptDelay ||
        MAX_CONN_ATTEMPT_DELAY;

    this.setPreferConnectionDirection(options.preferConnectionDirection || 'any');

    var self = this;

    function onIdentified(_, conn) {
        self.onIdentified(conn);
    }

    function onConnectionError(err, conn) {
        self.onConnectionError(err, conn);
    }

    function onConnectionClose(_, conn) {
        self.onConnectionClose(conn);
    }

    function onPendingChange(pending, conn) {
        self.onPendingChange(conn, pending);
    }

    function onReport() {
        if (!self.hostPort) {
            return;
        }

        var count = self.countConnections('out');
        if (self.channel.emitConnectionMetrics) {
            self.channel.emitFastStat(
                'tchannel.connections.active',
                'gauge',
                count,
                new stat.ConnectionsActiveTags(
                    self.channel.hostPort,
                    self.hostPort
                )
            );
        }

        self.reportTimer = self.timers.setTimeout(
            onReport, self.reportInterval
        );
    }
}
305594
public void setConnectTimeout(int millis) {
		ClientHttpRequestFactory f = getRequestFactory();
		if (f instanceof SimpleClientHttpRequestFactory) {
			((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
		else {
			((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
	}
330390
public void checkConnection() {
        long start = Time.currentTimeMillis();

        while (clientChannel == null) {

            tcpSocketConsumer.checkNotShutdown();

            if (start + timeoutMs > Time.currentTimeMillis())
                try {
                    condition.await(1, TimeUnit.MILLISECONDS);

                } catch (InterruptedException e) {
                    throw new IORuntimeException("Interrupted");
                }
            else
                throw new IORuntimeException("Not connected to " + socketAddressSupplier);
        }

        if (clientChannel == null)
            throw new IORuntimeException("Not connected to " + socketAddressSupplier);
    }
110817
private final void checkForDeadConnections(final long now) {
        final ArrayList<Pair<Connection, Integer>> connectionsToRemove = new ArrayList<Pair<Connection, Integer>>();
        for (final ClientInterfaceHandleManager cihm : m_cihm.values()) {
            // Internal connections don't implement calculatePendingWriteDelta(), so check for real connection first
            if (VoltPort.class == cihm.connection.getClass()) {
                final int delta = cihm.connection.writeStream().calculatePendingWriteDelta(now);
                if (delta > CLIENT_HANGUP_TIMEOUT) {
                    connectionsToRemove.add(Pair.of(cihm.connection, delta));
                }
            }
        }

        for (final Pair<Connection, Integer> p : connectionsToRemove) {
            Connection c = p.getFirst();
            networkLog.warn("Closing connection to " + c +
                    " because it hasn't read a response that was pending for " +  p.getSecond() + " milliseconds");
            c.unregister();
        }
    }
268320
public void connect(SocketAddress endpoint, int timeout) throws IOException {
    String filename;
    if (host == null || host.equals("localhost")) {
      filename = "\\\\.\\pipe\\" + name;
    } else {
      filename = "\\\\" + host + "\\pipe\\" + name;
    }

    //use a default timeout of 100ms if no timeout set.
    int usedTimeout = timeout == 0 ? 100 : timeout;
    long initialNano = System.nanoTime();
    do {
      try {
        file = new RandomAccessFile(filename, "rw");
        break;
      } catch (FileNotFoundException fileNotFoundException) {
        try {
          //using JNA if available
          Kernel32.INSTANCE.WaitNamedPipe(filename, timeout);
          //then retry connection
          file = new RandomAccessFile(filename, "rw");
        } catch (Throwable cle) {
          // in case JNA not on classpath, then wait 10ms before next try.
          if (System.nanoTime() - initialNano > TimeUnit.MILLISECONDS.toNanos(usedTimeout)) {
            if (timeout == 0) {
              throw new FileNotFoundException(fileNotFoundException.getMessage()
                  + "\nplease consider set connectTimeout option, so connection can retry having access to named pipe. "
                  + "\n(Named pipe can throw ERROR_PIPE_BUSY error)");
            }
            throw fileNotFoundException;
          }
          try {
            TimeUnit.MILLISECONDS.sleep(5);
          } catch (InterruptedException interrupted) {
            IOException ioException = new IOException(
                "Interruption during connection to named pipe");
            ioException.initCause(interrupted);
            throw ioException;
          }
        }
      }
    } while (true);

    is = new InputStream() {
      @Override
      public int read(byte[] bytes, int off, int len) throws IOException {
        return file.read(bytes, off, len);
      }

      @Override
      public int read() throws IOException {
        return file.read();
      }

      @Override
      public int read(byte[] bytes) throws IOException {
        return file.read(bytes);
      }
    };

    os = new OutputStream() {
      @Override
      public void write(byte[] bytes, int off, int len) throws IOException {
        file.write(bytes, off, len);
      }

      @Override
      public void write(int value) throws IOException {
        file.write(value);
      }

      @Override
      public void write(byte[] bytes) throws IOException {
        file.write(bytes);
      }
    };
  }
366649
public void probe(long timeoutInMs) {
    long start = System.nanoTime();

    try {
      while (!condition.call() && (elapsedMs(start) < timeoutInMs)) {
        Thread.yield();
      }

      if (!condition.call()) {
        throw new IllegalStateException("probe condition not true after " + timeoutInMs);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
957250
public static void sendNetStreamStatus(IConnection conn, String statusCode, String description, String name, String status, Number streamId) {
        if (conn instanceof RTMPConnection) {
            Status s = new Status(statusCode);
            s.setClientid(streamId);
            s.setDesciption(description);
            s.setDetails(name);
            s.setLevel(status);
            // get the channel
            RTMPConnection rtmpConn = (RTMPConnection) conn;
            Channel channel = rtmpConn.getChannel(rtmpConn.getChannelIdForStreamId(streamId));
            channel.sendStatus(s);
        } else {
            throw new RuntimeException("Connection is not RTMPConnection: " + conn);
        }
    }
275214
public String getHostAndPort()
  {
    if (enablePlaintextPort) {
      if (plaintextPort < 0) {
        return HostAndPort.fromString(host).toString();
      } else {
        return HostAndPort.fromParts(host, plaintextPort).toString();
      }
    }
    return null;
  }
927368
public void setConnectTimeout(int timeout) {
		Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
		getHttpClient().getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
	}
374261
public static boolean isSocketAlive(final SocketAddress socketAddress, final int timeoutMsecs) {
        final Socket socket = new Socket();
        try {
            socket.connect(socketAddress, timeoutMsecs);
            socket.close();
            return true;
        } catch (final SocketTimeoutException exception) {
            return false;
        } catch (final IOException exception) {
            return false;
        }
    }
438890
public static boolean bindPort(Session session, String remoteHost, int remotePort, int localPort) throws JschRuntimeException {
		if (session != null && session.isConnected()) {
			try {
				session.setPortForwardingL(localPort, remoteHost, remotePort);
			} catch (JSchException e) {
				throw new JschRuntimeException(e, "From [{}] mapping to [{}] error！", remoteHost, localPort);
			}
			return true;
		}
		return false;
	}