Tabnine Logo
Socket.connect
Code IndexAdd Tabnine to your IDE (free)

How to use
connect
method
in
java.net.Socket

Best Java code snippets using java.net.Socket.connect (Showing top 20 results out of 7,875)

Refine searchRefine arrow

  • Socket.<init>
  • InetSocketAddress.<init>
  • Socket.getOutputStream
  • Socket.close
  • Socket.getInputStream
  • Socket.setSoTimeout
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;
}
java.netSocketconnect

Javadoc

Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr.

Popular methods of Socket

  • close
    Closes the socket. It is not possible to reconnect or rebind to this socket thereafter which means a
  • <init>
    Creates an unconnected socket with the given socket implementation.
  • getOutputStream
    Returns an output stream to write data into this socket.
  • getInputStream
    Returns an input stream to read data from this socket.
  • setSoTimeout
    Sets this socket's SocketOptions#SO_TIMEOUT in milliseconds. Use 0 for no timeout. To take effect, t
  • getInetAddress
    Returns the IP address of the target host this socket is connected to, or null if this socket is not
  • setTcpNoDelay
    Sets this socket's SocketOptions#TCP_NODELAY option.
  • getPort
    Returns the port number of the target host this socket is connected to, or 0 if this socket is not y
  • isClosed
    Returns whether this socket is closed.
  • getRemoteSocketAddress
    Returns the remote address and port of this socket as a SocketAddress or null if the socket is not c
  • setKeepAlive
    Sets this socket's SocketOptions#SO_KEEPALIVE option.
  • isConnected
    Returns whether this socket is connected to a remote host.
  • setKeepAlive,
  • isConnected,
  • bind,
  • setSoLinger,
  • setSendBufferSize,
  • setReceiveBufferSize,
  • getLocalAddress,
  • getLocalPort,
  • shutdownOutput

Popular in Java

  • Reactive rest calls using spring rest template
  • scheduleAtFixedRate (ScheduledExecutorService)
  • scheduleAtFixedRate (Timer)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • ObjectMapper (com.fasterxml.jackson.databind)
    ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Pl
  • MessageDigest (java.security)
    Uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence.
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • NoSuchElementException (java.util)
    Thrown when trying to retrieve an element past the end of an Enumeration or Iterator.
  • TreeSet (java.util)
    TreeSet is an implementation of SortedSet. All optional operations (adding and removing) are support
  • JList (javax.swing)
  • Github Copilot alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now