Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket() 

Source Link

Document

Creates an unconnected Socket.

Usage

From source file:hudson.util.NoClientBindProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//from  w  ww.  j a va 2  s .c om
 * This method employs several techniques to circumvent the limitations of older JREs that 
 * do not support connect timeout. When running in JRE 1.4 or above reflection is used to 
 * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older 
 * JREs 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 localAddress the local host name/IP to bind the socket to, ignored
 * @param localPort the port on the local machine, ignored
 * @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
 * @throws ConnectTimeoutException if socket cannot be connected within the
 *  given time limit
 * 
 * @since 3.0
 */
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");
    }
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        // ignore the local address/port for binding
        return createSocket(host, port);
    } else {
        Socket s = new Socket();
        s.connect(new InetSocketAddress(host, port), timeout);
        return s;
    }
}

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  w  ww.  j a  v  a2 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:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java

/** Open a connexion to each Stack */
public boolean open() throws Exception {
    if (this.secure) {
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {//  w w  w  . j ava 2 s . c  o m
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }

    this.startTimestamp = System.currentTimeMillis();

    if (null != this.socketServerHttp) {
        ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp);
    } else {

        String host = this.getRemoteHost();
        int port = this.getRemotePort();

        DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection();

        Socket socket;

        if (this.secure) {
            // Create a trust manager that does not validate certificate chains like the default TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, null);

            socket = sslContext.getSocketFactory().createSocket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, true);
        } else {
            //
            // Create a TCP non secure socket
            //                
            socket = new Socket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, false);
        }

        //
        // Bind the socket to the local address
        //
        String localHost = this.getLocalHost();
        int localPort = initialLocalport;

        if (null != localHost) {
            socket.bind(new InetSocketAddress(localHost, localPort));
        } else {
            socket.bind(new InetSocketAddress(localPort));
        }

        socket.setReceiveBufferSize(65536);
        socket.connect(new InetSocketAddress(host, port));

        this.setLocalPort(socket.getLocalPort());

        HttpParams params = new BasicHttpParams();
        defaultHttpClientConnection.bind(socket, params);

        this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this);

        ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp);
    }
    return true;
}

From source file:fr.treeptik.cloudunit.utils.PortUtils.java

private boolean isPortOpened(String ip, Integer port) {
    try {/* www. java2 s .co  m*/
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), 500);
        socket.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:android.core.SSLSocketTest.java

/**
 * Does a number of HTTPS requests on some host and consumes the response.
 * We don't use the HttpsUrlConnection class, but do this on our own
 * with the SSLSocket class. This gives us a chance to test the basic
 * behavior of SSL.//  w w w .  ja  v  a 2s .c om
 *
 * @param host      The host name the request is being sent to.
 * @param port      The port the request is being sent to.
 * @param path      The path being requested (e.g. "/index.html").
 * @param outerLoop The number of times we reconnect and do the request.
 * @param innerLoop The number of times we do the request for each
 *                  connection (using HTTP keep-alive).
 * @param delay     The delay after each request (in seconds).
 * @throws IOException When a problem occurs.
 */
private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path,
        int outerLoop, int innerLoop, int delay, int timeout) throws IOException {
    InetSocketAddress address = new InetSocketAddress(host, port);

    for (int i = 0; i < outerLoop; i++) {
        // Connect to the remote host
        Socket socket = secure ? socketFactory.createSocket() : new Socket();
        if (timeout >= 0) {
            socket.setKeepAlive(true);
            socket.setSoTimeout(timeout * 1000);
        }
        socket.connect(address);

        // Get the streams
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output);

        try {
            DataInputStream input = new DataInputStream(socket.getInputStream());
            try {
                for (int j = 0; j < innerLoop; j++) {
                    android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1");

                    // Send a request
                    writer.println("GET https://" + host + path + " HTTP/1.1\r");
                    writer.println("Host: " + host + "\r");
                    writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r");
                    writer.println("\r");
                    writer.flush();

                    int length = -1;
                    boolean chunked = false;

                    String line = input.readLine();

                    if (line == null) {
                        throw new IOException("No response from server");
                        // android.util.Log.d("SSLSocketTest", "No response from server");
                    }

                    // Consume the headers, check content length and encoding type
                    while (line != null && line.length() != 0) {
                        //                    System.out.println(line);
                        int dot = line.indexOf(':');
                        if (dot != -1) {
                            String key = line.substring(0, dot).trim();
                            String value = line.substring(dot + 1).trim();

                            if ("Content-Length".equalsIgnoreCase(key)) {
                                length = Integer.valueOf(value);
                            } else if ("Transfer-Encoding".equalsIgnoreCase(key)) {
                                chunked = "Chunked".equalsIgnoreCase(value);
                            }

                        }
                        line = input.readLine();
                    }

                    assertTrue("Need either content length or chunked encoding", length != -1 || chunked);

                    // Consume the content itself
                    if (chunked) {
                        length = Integer.parseInt(input.readLine(), 16);
                        while (length != 0) {
                            byte[] buffer = new byte[length];
                            input.readFully(buffer);
                            input.readLine();
                            length = Integer.parseInt(input.readLine(), 16);
                        }
                        input.readLine();
                    } else {
                        byte[] buffer = new byte[length];
                        input.readFully(buffer);
                    }

                    // Sleep for the given number of seconds
                    try {
                        Thread.sleep(delay * 1000);
                    } catch (InterruptedException ex) {
                        // Shut up!
                    }
                }
            } finally {
                input.close();
            }
        } finally {
            writer.close();
        }
        // Close the connection
        socket.close();
    }
}

From source file:com.cyberway.issue.crawler.fetcher.HeritrixProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from ww  w  .j av  a 2 s  .c o m
 * <p>
 * This method employs several techniques to circumvent the limitations
 * of older JREs that do not support connect timeout. When running in
 * JRE 1.4 or above reflection is used to call
 * Socket#connect(SocketAddress endpoint, int timeout) method. When
 * executing in older JREs 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 localAddress the local host name/IP to bind the socket to
 * @param localPort 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
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 * @throws ConnectTimeoutException if socket cannot be connected within the
 *  given time limit
 *
 * @since 3.0
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    // Below code is from the DefaultSSLProtocolSocketFactory#createSocket
    // method only it has workarounds to deal with pre-1.4 JVMs.  I've
    // cut these out.
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    Socket socket = null;
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        socket = createSocket(host, port, localAddress, localPort);
    } else {
        socket = new Socket();
        ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY);
        InetAddress hostAddress = (cache != null) ? getHostAddress(cache, host) : null;
        InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port)
                : new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        try {
            socket.connect(address, timeout);
        } catch (SocketTimeoutException e) {
            // Add timeout info. to the exception.
            throw new SocketTimeoutException(
                    e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms.");
        }
        assert socket.isConnected() : "Socket not connected " + host;
    }
    return socket;
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *//*from ww w.  j  a  va2 s.  co m*/
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:ch.algotrader.adapter.ib.IBSession.java

private void waitAndConnect() {

    while (!isTerminated()) {

        Socket socket = new Socket();
        try {/*from   w  w  w  . j  a  v a  2 s  .co  m*/
            socket.connect(new InetSocketAddress(this.host, this.port), 5000);
            eConnect(socket, this.clientId);
            return;
        } catch (ConnectException e) {
            // do nothing, gateway is down
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("please start IB Gateway / TWS on port: {}", this.port);
            }
        } catch (IOException e) {
            LOGGER.error("connection error", e);
        }
        try {
            socket.close();
        } catch (IOException ignore) {
        }

        sleep();
    }

}

From source file:dbseer.old.middleware.MiddlewareSocket.java

public MiddlewareSocket() {
    txMap = new TransactionMap();
    socket = new Socket();
    lock = new Object();
}