Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

In this page you can find the example usage for java.net Socket connect.

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

From source file:org.apache.ambari.server.state.svccomphost.HBaseMasterPortScanner.java

protected boolean scan(String hostname) {
    try {/*w  w w.  j ava 2 s.c om*/
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), scanTimeoutMsc);
        socket.close();
        LOG.info(hostname + ":" + port + " HBASE_MASTER active");
        return true;
    } catch (ConnectException e) {
        LOG.info(hostname + ":" + port + " HBASE_MASTER passive");
        return false;
    } catch (Exception ex) {
        LOG.info(hostname + ":" + port + " HBASE_MASTER passive");
        LOG.error(ex);
        return false;
    }
}

From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  w  ww .j ava2  s.  c o  m*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName(), context);
        return sock;
    } else
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
}

From source file:com.ufasta.mobile.core.request.security.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.// w  w w .j a va  2  s . c o m
 * <p>
 * To circumvent the limitations of older JREs that do not support connect
 * timeout a controller thread is executed. The controller thread attempts
 * to create a new socket within the given limit of time. If socket
 * constructor does not return until the timeout expires, the controller
 * terminates and throws an {@link ConnectTimeoutException}
 * </p>
 * 
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @param clientHost
 *            the local host name/IP to bind the socket to
 * @param clientPort
 *            the port on the local machine
 * @param params
 *            {@link HttpConnectionParams Http connection parameters}
 * @return Socket a new socket
 * @throws IOException
 *             if an I/O error occurs while creating the socket
 * @throws UnknownHostException
 *             if the IP address of the host cannot be determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    }
    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.bind(localaddr);
    socket.connect(remoteaddr, timeout);
    return socket;
}

From source file:org.apache.hadoop.hdfs.server.namenode.JspHelper.java

public static DatanodeInfo bestNode(LocatedBlock blk) throws IOException {
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
    DatanodeInfo chosenNode = null;//w w  w  .jav  a  2s.  co m
    int failures = 0;
    Socket s = null;
    DatanodeInfo[] nodes = blk.getLocations();
    if (nodes == null || nodes.length == 0) {
        throw new IOException("No nodes contain this block");
    }
    while (s == null) {
        if (chosenNode == null) {
            do {
                chosenNode = nodes[rand.nextInt(nodes.length)];
            } while (deadNodes.contains(chosenNode));
        }
        int index = rand.nextInt(nodes.length);
        chosenNode = nodes[index];

        //just ping to check whether the node is alive
        InetSocketAddress targetAddr = NetUtils
                .createSocketAddr(chosenNode.getHost() + ":" + chosenNode.getInfoPort());

        try {
            s = new Socket();
            s.connect(targetAddr, HdfsConstants.READ_TIMEOUT);
            s.setSoTimeout(HdfsConstants.READ_TIMEOUT);
        } catch (IOException e) {
            deadNodes.add(chosenNode);
            s.close();
            s = null;
            failures++;
        }
        if (failures == nodes.length)
            throw new IOException("Could not reach the block containing the data. Please try again");

    }
    s.close();
    return chosenNode;
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void afterReadyInterestIsCleared() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/*from w  w  w  . j a  v a  2 s  . c  om*/
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:com.denimgroup.threadfix.remote.AcceptAllTrustManager.java

@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }//w w w  .j  av a 2  s .co  m

    int timeout = params.getConnectionTimeout();
    SocketFactory socketFactory = getSSLContext().getSocketFactory();

    if (timeout == 0) {
        return socketFactory.createSocket(host, port, localAddress, localPort);
    }

    else {
        Socket socket = socketFactory.createSocket();
        SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteAddr = new InetSocketAddress(host, port);
        socket.bind(localAddr);
        socket.connect(remoteAddr, timeout);
        return socket;
    }
}

From source file:org.codeartisans.proxilet.EasySSLProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }/*w  w  w  . j av  a2 s  .  c o m*/
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  w w  w . j a  va2 s.  c  om*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void noReadyCallbackIfInterestRemoved() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);//from   w  w  w.  j a va  2 s.c om
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });

    // Wait for registration, in other case we get unpredictable timing related results due to late registration
    while (key.get() == null) {
        Thread.sleep(10);
    }

    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    hub.hub().removeInterestAccept(key.get());
    // wait for the interest accept to be removed
    while ((key.get().interestOps() & SelectionKey.OP_ACCEPT) != 0) {
        Thread.sleep(10);
    }
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.hashes.HttpClient.java

@Override
public void run() {
    for (int i = 0; i < this.requests; i++) {

        Socket socket = null;
        OutputStream output = null;
        InputStream input = null;

        try {/*from w  ww  . j  a  v a 2 s.com*/
            socket = this.createUnconnectedSocket();
            this.applySettings(socket);
            socket.connect(new InetSocketAddress(this.target.getHostname(), this.target.getPort()),
                    this.target.getConnectTimeout());

            // write the entire byte array in one shot and close the stream.
            // In this situation, buffering would add extra overhead!
            output = socket.getOutputStream();
            output.write(this.payload);
            output.flush();

            if (this.waitForResponse && LOG.isInfoEnabled()) {
                input = socket.getInputStream();
                LOG.info(new String(ByteStreams.toByteArray(input), this.responseCharset));
            }
        } catch (final Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while injecting payload. " + e.getMessage(), e);
            }
        } finally {
            this.closeQuietly(output, input, socket);
        }
    }
}