java.net.Socket.connect()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(396)

本文整理了Java中java.net.Socket.connect()方法的一些代码示例,展示了Socket.connect()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.connect()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:connect

Socket.connect介绍

[英]Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr.
[中]将此套接字连接到SocketAddress remoteAddr指定的给定远程主机地址和端口。

代码示例

代码示例来源:origin: stackoverflow.com

public static boolean pingHost(String host, int port, int timeout) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port), timeout);
    return true;
  } catch (IOException e) {
    return false; // Either timeout or unreachable or failed DNS lookup.
  }
}

代码示例来源:origin: dropwizard/dropwizard

@Override
  OutputStream openNewOutputStream() throws IOException {
    final Socket socket = socketFactory.createSocket();
    // Prevent automatic closing of the connection during periods of inactivity.
    socket.setKeepAlive(true);
    // Important not to cache `InetAddress` in case the host moved to a new IP address.
    socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), connectionTimeoutMs);
    return new BufferedOutputStream(socket.getOutputStream(), sendBufferSize);
  }
}

代码示例来源:origin: mpusher/mpush

public static boolean checkHealth(String ip, int port) {
  try {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(ip, port), 1000);
    socket.close();
    return true;
  } catch (IOException e) {
    return false;
  }
}

代码示例来源:origin: oldmanpushcart/greys-anatomy

/**
 * 激活网络
 */
private Socket connect(InetSocketAddress address) throws IOException {
  final Socket socket = new Socket();
  socket.setSoTimeout(0);
  socket.connect(address, _1MIN);
  socket.setKeepAlive(true);
  socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  return socket;
}

代码示例来源:origin: internetarchive/heritrix3

public Socket createSocket(InetAddress host, int port)
    throws IOException {
  Socket sock = createSocket();
  sock.connect(new InetSocketAddress(host, port), connectTimeoutMs);
  return sock;
}

代码示例来源:origin: spring-projects/spring-data-examples

@Override
  protected void before() throws Throwable {

    Socket socket = SocketFactory.getDefault().createSocket();
    try {
      socket.connect(new InetSocketAddress(host, port), Math.toIntExact(timeout.toMillis()));
    } catch (IOException e) {
      throw new AssumptionViolatedException(
          String.format("Couchbase not available on on %s:%d. Skipping tests.", host, port), e);
    } finally {
      socket.close();
    }
  }
}

代码示例来源:origin: apache/nifi

private SocketChannel createChannel() throws IOException {
  final SocketChannel socketChannel = SocketChannel.open();
  try {
    socketChannel.configureBlocking(true);
    final Socket socket = socketChannel.socket();
    socket.setSoTimeout(timeoutMillis);
    socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort()));
    socket.setSoTimeout(timeoutMillis);
    return socketChannel;
  } catch (final Exception e) {
    try {
      socketChannel.close();
    } catch (final Exception closeException) {
      e.addSuppressed(closeException);
    }
    throw e;
  }
}

代码示例来源:origin: fabric8io/docker-maven-plugin

@Override
public boolean check() {
  Iterator<InetSocketAddress> iter = pending.iterator();
  while (iter.hasNext()) {
    InetSocketAddress address = iter.next();
    try {
      Socket s = new Socket();
      s.connect(address, TCP_PING_TIMEOUT);
      s.close();
      iter.remove();
    } catch (IOException e) {
      // Ports isn't opened, yet. So don't remove from queue.
      // Can happen and is part of the flow
    }
  }
  return pending.isEmpty();
}

代码示例来源:origin: alibaba/canal

public static BioSocketChannel open(SocketAddress address) throws Exception {
  Socket socket = new Socket();
  socket.setSoTimeout(BioSocketChannel.SO_TIMEOUT);
  socket.setTcpNoDelay(true);
  socket.setKeepAlive(true);
  socket.setReuseAddress(true);
  socket.connect(address, BioSocketChannel.DEFAULT_CONNECT_TIMEOUT);
  return new BioSocketChannel(socket);
}

代码示例来源:origin: apache/zookeeper

/**
 * Invokes initiateConnection for testing purposes
 *
 * @param sid
 */
public void testInitiateConnection(long sid) throws Exception {
  LOG.debug("Opening channel to server " + sid);
  Socket sock = new Socket();
  setSockOpts(sock);
  sock.connect(self.getVotingView().get(sid).electionAddr, cnxTO);
  initiateConnection(sock, sid);
}

代码示例来源:origin: apache/zookeeper

public static void ruok(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[4];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: MovingBlocks/Terasology

/**
   * @return the ping time in milliseconds
   */
  @Override
  public Long call() throws IOException {
    Instant start = Instant.now();
    try (Socket sock = new Socket()) {
      InetSocketAddress endpoint = new InetSocketAddress(address, port);
      // One alternative is InetAddress.isReachable(), but it seems to require
      // root privileges under some operating systems
      sock.connect(endpoint, timeout);
      Instant end = Instant.now();
      sock.close();
      long millis = Duration.between(start, end).toMillis();
      return millis;
    }
  }
}

代码示例来源:origin: prestodb/presto

private static boolean isPortOpen(String host, Integer port)
  {
    try (Socket socket = new Socket()) {
      socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), 1000);
      return true;
    }
    catch (ConnectException | SocketTimeoutException e) {
      return false;
    }
    catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
}

代码示例来源:origin: voldemort/voldemort

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
    throws IOException, UnknownHostException {
  Socket socket = applySettings(createSocket());
  socket.bind(new InetSocketAddress(host, localPort));
  socket.connect(new InetSocketAddress(host, port), socketTimeout);
  return socket;
}

代码示例来源:origin: apache/zookeeper

private Socket connectWithoutSSL() throws IOException, InterruptedException {
  Socket socket = null;
  int retries = 0;
  while (retries < MAX_RETRIES) {
    try {
      socket = new Socket();
      socket.setSoTimeout(TIMEOUT);
      socket.connect(localServerAddress, TIMEOUT);
      break;
    } catch (ConnectException connectException) {
      connectException.printStackTrace();
      forceClose(socket);
      socket = null;
      Thread.sleep(TIMEOUT);
    }
    retries++;
  }
  Assert.assertNotNull("Failed to connect to server without SSL", socket);
  return socket;
}

代码示例来源:origin: voldemort/voldemort

public NonRespondingSocketService(int port) throws IOException {
  // server socket with single element backlog queue (1) and dynamically
  // allocated port (0)
  serverSocket = new ServerSocket(port, 1);
  // just get the allocated port
  port = serverSocket.getLocalPort();
  // fill backlog queue by this request so consequent requests will be
  // blocked
  new Socket().connect(serverSocket.getLocalSocketAddress());
}

代码示例来源:origin: apache/zookeeper

public static void kill(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[4];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: stackoverflow.com

public static Future<Boolean> portIsOpen(final ExecutorService es, final String ip, final int port, final int timeout) {
 return es.submit(new Callable<Boolean>() {
   @Override public Boolean call() {
    try {
     Socket socket = new Socket();
     socket.connect(new InetSocketAddress(ip, port), timeout);
     socket.close();
     return true;
    } catch (Exception ex) {
     return false;
    }
   }
  });
}

代码示例来源:origin: stackoverflow.com

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

代码示例来源:origin: voldemort/voldemort

@Override
public Socket createSocket(InetAddress address,
              int port,
              InetAddress localAddress,
              int localPort) throws IOException {
  Socket socket = applySettings(createSocket());
  socket.bind(new InetSocketAddress(address, localPort));
  socket.connect(new InetSocketAddress(localAddress, port), socketTimeout);
  return socket;
}

相关文章