The contract is similar to {@link SocketChannel#connect(SocketAddress)}
with a timeout.

@see SocketChannel#connect(SocketAddress)

@param channel - this should be a {@link SelectableChannel}
@param endpoint
@throws IOException
551043
static void connect(SocketChannel channel, 
                      SocketAddress endpoint, int timeout) throws IOException {
    
    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
      channel.configureBlocking(false);
    }
    
    try { 
      if (channel.connect(endpoint)) {
        return;
      }

      long timeoutLeft = timeout;
      long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout): 0;
      
      while (true) {
        // we might have to call finishConnect() more than once
        // for some channels (with user level protocols)
        
        int ret = selector.select((SelectableChannel)channel, 
                                  SelectionKey.OP_CONNECT, timeoutLeft);
        
        if (ret > 0 && channel.finishConnect()) {
          return;
        }
        
        if (ret == 0 ||
            (timeout > 0 &&  
              (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
          throw new SocketTimeoutException(
                    timeoutExceptionString(channel, timeout, 
                                           SelectionKey.OP_CONNECT));
        }
      }
    } catch (IOException e) {
      // javadoc for SocketChannel.connect() says channel should be closed.
      try {
        channel.close();
      } catch (IOException ignored) {}
      throw e;
    } finally {
      if (blockingOn && channel.isOpen()) {
        channel.configureBlocking(true);
      }
    }
  }
89536
public static void setChannelOptions(Channel channel, EndpointConfig config) {
        ChannelOptions options = channel.options();
        options.setOption(DIRECT_BUF, config.isSocketBufferDirect())
               .setOption(TCP_NODELAY, config.isSocketTcpNoDelay())
               .setOption(SO_KEEPALIVE, config.isSocketKeepAlive())
               .setOption(SO_SNDBUF, config.getSocketSendBufferSizeKb() * KILO_BYTE)
               .setOption(SO_RCVBUF, config.getSocketRcvBufferSizeKb() * KILO_BYTE)
               .setOption(SO_LINGER, config.getSocketLingerSeconds());
    }
1194287
public void writeTo(SocketChannel channel) throws IOException {
        channel.write(buffer);

        // only if buffer is empty
        if (buffer.remaining() == 0) {
            buffer.clear();
            state = BufferState.READY_TO_WRITE;
        }
    }
510516
public void init(VirtualConnection inVC, HttpOutboundChannel channel) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Init on link: " + this + " " + inVC);
        }
        super.init(inVC);
        this.myChannel = channel;
        this.bIsActive = true;
        setEnableReconnect(this.myChannel.getHttpConfig().allowsRetries());
        setAllowReconnect(true);
    }
1008250
protected MessageChannel resolveChannelName(String channelName, TestContext context) {
        if (endpointConfiguration.getChannelResolver() == null) {
            if (endpointConfiguration.getBeanFactory() != null) {
                endpointConfiguration.setChannelResolver(new BeanFactoryChannelResolver(endpointConfiguration.getBeanFactory()));
            } else {
                endpointConfiguration.setChannelResolver(new BeanFactoryChannelResolver(context.getApplicationContext()));
            }
        }

        return endpointConfiguration.getChannelResolver().resolveDestination(channelName);
    }
186947
@Override
  public void channelInactive(ChannelHandlerContext ctx) {
    Status status = Status.UNAVAILABLE.withDescription(
        "Connection closed while performing protocol negotiation for " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
  }
267532
synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
        synchronized (fdLock) {
            if (!closePending && (socket == null || !socket.isBound())) {
                NetHooks.beforeTcpConnect(fd, address, port);
            }
        }
        try {
            BlockGuard.getThreadPolicy().onNetwork();
            socketConnect(address, port, timeout);
            /* socket may have been closed during poll/select */
            synchronized (fdLock) {
                if (closePending) {
                    throw new SocketException ("Socket closed");
                }
            }
            // If we have a ref. to the Socket, then sets the flags
            // created, bound & connected to true.
            // This is normally done in Socket.connect() but some
            // subclasses of Socket may call impl.connect() directly!
            if (socket != null) {
                socket.setBound();
                socket.setConnected();
            }
        } catch (IOException e) {
            close();
            throw e;
        }
    }
1200642
public static SSLServerSocketChannel open(SocketAddress address, SSLContext sslContext) throws IOException
    {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(address);
        SSLServerSocketChannel sslSocketChannel = new SSLServerSocketChannel(serverSocketChannel, sslContext);
        return sslSocketChannel;
    }
340727
public boolean connectImpl(String address, int port)
    throws IOException
  {
    _socketTimeout = 600000;

    _nativeFd = -1;
    _isClosed.set(false);

    synchronized (_writeLock) {
      boolean isConnect = nativeConnect(_socketFd, address, port);

      return isConnect;
    }
  }
777908
void registerAndConnect(SocketChannel sock, InetSocketAddress addr)
            throws IOException {
        selectionKey = sock.register(selector, SelectionKey.OP_CONNECT);

        boolean immediateConnect = sock.connect(addr);
        if(LOGGER.isTraceEnabled()){
            LOGGER.trace("Connect to host=" + addr.getHostName() + ", hostString=" + addr.getHostString() + ", port=" + addr.getPort() + ", all=" + addr.getAddress() + ", local=" + sock.socket().getLocalSocketAddress());
        }
        if (immediateConnect) {
            onConnectSucceeded();
        }


    }
172404
private SocketChannel connectToHost(SocketAddress hostAddr)
            throws IOException
    {
        SocketChannel socket = null;
        while (socket == null) {
            try {
                socket = SocketChannel.open(hostAddr);
            }
            catch (java.net.ConnectException e) {
                LOG.warn("Joining host failed: " + e.getMessage() + " retrying..");
                try {
                    Thread.sleep(250); //  milliseconds
                }
                catch (InterruptedException dontcare) {}
            }
        }
        return socket;
    }
507954
private synchronized void createChannel(String channel) {
        if (!channelExists(channel)) {
            Queue queue = new Queue(channel, true, false, true);
            admin.declareQueue(queue);
            Binding binding = new Binding(channel, DestinationType.QUEUE, exchange.getName(), channel + ".#", null);
            admin.declareBinding(binding);
        }
    }
436388
private void closeSocketChannel(SocketChannel sc) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            try {
                Tr.event(this, tc, "Closing connection, local: " + sc.socket().getLocalSocketAddress() + " remote: " + sc.socket().getRemoteSocketAddress());
            } catch (Throwable t) {
                // protect against JDK PK42970 throwing illegal arg
            }
        }

        try {
            sc.close();
        } catch (IOException ioe) {

            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(this, tc, "IOException caught while closing connection " + ioe);
            }
        }
    }
139088
public void connect(
		final String endpoint,
		final Callback<? super HttpSocket> onConnect,
		final Callback<? super Exception> onError
	) {
		executors.getUnbounded().submit(
			new Runnable() {
				@Override
				public void run() {
					try {
						// Build request bytes
						AoByteArrayOutputStream bout = new AoByteArrayOutputStream();
						try {
							try (DataOutputStream out = new DataOutputStream(bout)) {
								out.writeBytes("action=connect");
							}
						} finally {
							bout.close();
						}
						long connectTime = System.currentTimeMillis();
						URL endpointURL = new URL(endpoint);
						HttpURLConnection conn = (HttpURLConnection)endpointURL.openConnection();
						conn.setAllowUserInteraction(false);
						conn.setConnectTimeout(CONNECT_TIMEOUT);
						conn.setDoOutput(true);
						conn.setFixedLengthStreamingMode(bout.size());
						conn.setInstanceFollowRedirects(false);
						conn.setReadTimeout(CONNECT_TIMEOUT);
						conn.setRequestMethod("POST");
						conn.setUseCaches(false);
						// Write request
						OutputStream out = conn.getOutputStream();
						try {
							out.write(bout.getInternalByteArray(), 0, bout.size());
							out.flush();
						} finally {
							out.close();
						}
						// Get response
						int responseCode = conn.getResponseCode();
						if(responseCode != 200) throw new IOException("Unexpect response code: " + responseCode);
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got connection");
						DocumentBuilder builder = builderFactory.newDocumentBuilder();
						Element document = builder.parse(conn.getInputStream()).getDocumentElement();
						if(!"connection".equals(document.getNodeName())) throw new IOException("Unexpected root node name: " + document.getNodeName());
						Identifier id = Identifier.valueOf(document.getAttribute("id"));
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got id=" + id);
						HttpSocket httpSocket = new HttpSocket(
							HttpSocketClient.this,
							id,
							connectTime,
							endpointURL
						);
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: adding socket");
						addSocket(httpSocket);
						if(onConnect!=null) {
							if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onConnect");
							onConnect.call(httpSocket);
						}
					} catch(Exception exc) {
						if(onError!=null) {
							if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onError");
							onError.call(exc);
						}
					}
				}
			}
		);
	}
1088437
public void setChannel(PrivateChannel channel) {
        if (this.channel != channel) {
            if (this.channel != null) {
                ((Cleanupable) this.channel).cleanup();
            }
            this.channel = channel;
        }
    }
761942
@Override
  public void probeChannel() {
    if (closed) return;
    
    try {
      final SocketChannel channel = preparedChannel();
      if (channel != null) {
        readConsume(channel);
      }
    } catch (IOException e) {
      logger.log("Failed to read channel selector for " + address + " because: " + e.getMessage(), e);
    }
  }
976799
@Override
  public void setEndpointAddress(Stub soapClient, String endpointAddress) {
    soapClient._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
  }