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:com.gsf.dowload.nfe.HSProtocolSocketFactory.java

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");
    }/*from www  . ja v  a 2s. co m*/
    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);
    try {
        socket.connect(remoteaddr, timeout);
    } catch (Throwable t) {
        Logger.getLogger(HSProtocolSocketFactory.class.getName()).log(Level.SEVERE, null, t);
        throw new ConnectTimeoutException("Erro na conexao", t);
    }

    return socket;
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultSSLProtocolSocketFactory.java

/**
 * {@inheritDoc}/*from   w  w  w  . j ava2s .  c om*/
 */
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Check.notNull(params, "params"); //$NON-NLS-1$

    final int timeout = params.getConnectionTimeout();

    final Socket socket = getSocketFactory(params).createSocket();
    configureSNI(socket, host);
    socket.bind(new InetSocketAddress(localAddress, localPort));
    socket.connect(new InetSocketAddress(host, port), timeout);
    return socket;
}

From source file:com.utest.domain.service.util.TrustedSSLUtil.java

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");
    }/*from   w  w  w . jav  a 2  s  .  c om*/
    final int timeout = params.getConnectionTimeout();
    final SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        final Socket socket = socketfactory.createSocket();
        final SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        final SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:org.jdesktop.http.SSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/* w  w  w  .j a v  a2 s  .c  o m*/
 * 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(host).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.trsst.client.AnonymSSLSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit./*from   ww w.j  a va  2  s  . c  om*/
 * 
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @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"); //$NON-NLS-1$

    /* Determine Connection Timeout */
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();

    /* Timeout is unlimited */
    if (timeout == 0)
        return socketfactory.createSocket(host, port, localAddress, localPort);

    /* Timeout is defined */
    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.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

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 a 2  s .co m
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        return createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = factory.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:edu.vt.middleware.gator.server.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors.//from w  ww.  j  a  va 2  s .c o m
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(new MockEvent(TEST_MESSAGE));
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    // Ensure test message was written to file
    Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE));
}

From source file:com.axelor.apps.base.service.MapService.java

private boolean testInternet(String site) {
    Socket socket = new Socket();
    InetSocketAddress address = new InetSocketAddress(site, 80);
    try {/*from  w  w w .j a  va2  s  .  co m*/
        socket.connect(address, 3000);
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
        }
    }
}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors.//from  www  .ja  va  2  s  .  c om
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final LoggingEvent event = new LoggingEvent(TEST_CATEGORY, Logger.getLogger(TEST_CATEGORY), Level.DEBUG,
                TEST_MESSAGE, null);
        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(event);
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    for (AppenderConfig appender : testProject.getAppenders()) {
        final String logFilePath = FileHelper.pathCat(CLIENT_ROOT_DIR, testProject.getName(),
                appender.getAppenderParam("file").getValue());
        final String contents = readTextFile(logFilePath);
        Assert.assertTrue(contents.contains(TEST_MESSAGE));
    }
}

From source file:org.psit.transwatcher.TransWatcher.java

private void startConnectionKeepAliveWatchDog(final Socket newImageListenerSocket) {
    watchDogThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true) {
                    Thread.sleep(5000);
                    InetSocketAddress addr = new InetSocketAddress(newImageListenerSocket.getInetAddress(), 80);
                    Socket s = new Socket();
                    s.connect(addr, 1000);
                    s.close();/*  w  ww .j  ava 2 s  .com*/
                    notifyMessage("WatchDog ping.");
                }
            } catch (InterruptedException e) {
                notifyMessage("WatchDog interrupted");
            } catch (IOException e) {
                notifyMessage("WatchDog: Connection to card lost.");
                try {
                    newImageListenerSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }

        };
    }, "ConnectionWatchDog");
    watchDogThread.start();
}