Example usage for java.net Socket setSoTimeout

List of usage examples for java.net Socket setSoTimeout

Introduction

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

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_TIMEOUT SO_TIMEOUT with the specified timeout, in milliseconds.

Usage

From source file:com.newrelic.agent.deps.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.java

@Override
public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }/*from   ww  w.jav a  2 s. c om*/
    final InetAddress[] addresses = host.getAddress() != null ? new InetAddress[] { host.getAddress() }
            : this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setSoTimeout(socketConfig.getSoTimeout());
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
        sock.setKeepAlive(socketConfig.isSoKeepAlive());
        final int linger = socketConfig.getSoLinger();
        if (linger >= 0) {
            sock.setSoLinger(true, linger);
        }
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        } catch (final NoRouteToHostException ex) {
            if (last) {
                throw ex;
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:com.cazoodle.crawl.DummySSLProtocolSocketFactory.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");
    }//w w w. j  a  v a2  s. c o  m
    int timeout = params.getConnectionTimeout();
    if (timeout > 0) {
        Socket socket = getSSLContext().getSocketFactory().createSocket();
        socket.bind(new InetSocketAddress(localAddress, localPort));
        socket.setSoTimeout(timeout);
        socket.connect(new InetSocketAddress(getInetAddress(host), port), timeout);
        return socket;
    } else {
        return createSocket(host, port, localAddress, localPort);
    }
}

From source file:org.rhq.enterprise.server.plugins.jdr.JdrServerPluginComponent.java

@Override
public void start() {

    try {/*from ww w.j  ava2s  .  co  m*/
        server = new ServerSocket(LISTEN, 1, InetAddress.getByName(null));
        serverThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.debug("Listening on " + LISTEN);
                    while (true) {
                        Socket socket = server.accept();
                        socket.setSoTimeout(SOCK_TIMEOUT);
                        log.debug("Connection successfull");
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String inputLine = null;
                        try {
                            char[] buffer = new char[TOKEN_SIZE];
                            int read = in.read(buffer);
                            if (read == TOKEN_SIZE) {
                                inputLine = new String(buffer);
                                if (inputLine.equals(getAccessToken())) {
                                    log.debug("Client authorized");
                                    out.println(getSystemInfo());
                                    log.debug("SystemInfo returned");
                                    setAccessToken(); // regenerate
                                } else {
                                    log.debug("Invalid token recieved");
                                    out.println("Bye!");
                                }
                            } else {
                                log.debug("Invalid token recieved");
                                out.println("Bye!");
                            }
                        } catch (SocketTimeoutException ex) {
                            log.debug("Client timed out to send token");
                            out.println("Bye!");
                        }
                        in.close();
                        out.close();
                        socket.close();
                    }
                } catch (SocketException e) {
                    // listening was canceled
                } catch (Exception e) {
                    log.error("Socket server interrupted", e);
                }
            }
        });
        serverThread.start();
    } catch (Exception ex) {
        log.error(ex);
    }
}

From source file:com.googlecode.jsendnsca.NagiosPassiveCheckSender.java

private Socket connectedToNagios() throws IOException {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(nagiosSettings.getNagiosHost(), nagiosSettings.getPort()),
            nagiosSettings.getConnectTimeout());
    socket.setSoTimeout(nagiosSettings.getTimeout());
    return socket;
}

From source file:org.jboss.test.kerberos.KerberosSetup.java

protected void waitForStop() throws Exception {
    final ServerSocket srv = new ServerSocket(SERVER_PORT);
    boolean isStop = false;
    do {//w  w  w .ja  v  a 2  s  . c o  m
        // Wait for connection from client.
        Socket socket = srv.accept();
        System.out.println("Incomming connection.");
        socket.setSoTimeout(SOCKET_TIMEOUT);
        BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        try {
            isStop = STOP_CMD.equals(rd.readLine());
        } finally {
            rd.close();
        }
        System.out.println("Stop command: " + isStop);
        socket.close();
    } while (!isStop);
    IOUtils.closeQuietly(srv);
}

From source file:com.tomcat.monitor.zabbix.ZabbixSender.java

public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host,
        final String key, final String value) throws IOException {

    final byte[] response = new byte[1024];

    final long start = System.currentTimeMillis();

    final int TIMEOUT = zabbixTimeout * 1000;

    final StringBuilder message = new StringBuilder("<req><host>");
    message.append(new String(Base64.encodeBase64(host.getBytes())));
    message.append("</host><key>");
    message.append(new String(Base64.encodeBase64(key.getBytes())));
    message.append("</key><data>");
    message.append(new String(Base64.encodeBase64(value.getBytes())));
    message.append("</data></req>");

    if (log.isDebugEnabled()) {
        log.debug("sending " + message);
    }/*from   www .  j av a2s. co m*/

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    try {
        zabbix = new Socket(zabbixServer, zabbixPort);
        zabbix.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(zabbix.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = zabbix.getInputStream();
        final int read = in.read(response);
        if (log.isDebugEnabled()) {
            log.debug("received " + new String(response));
        }
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'");
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (zabbix != null) {
            zabbix.close();
        }
    }
    log.info("send() " + (System.currentTimeMillis() - start) + " ms");
}

From source file:eu.alefzero.owncloud.authenticator.EasySSLSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit./*from w  w  w .  j  ava2 s . co 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) {
        Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
        socket.setSoTimeout(params.getSoTimeout());
        return socket;
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.setSoTimeout(params.getSoTimeout());
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:voldemort.store.socket.SocketPoolableObjectFactory.java

/**
 * Create a socket for the given host/port
 *///from   w  ww  .j a v  a  2  s  . co  m
public Object makeObject(Object key) throws Exception {
    SocketDestination dest = (SocketDestination) key;
    Socket socket = new Socket();
    socket.setReceiveBufferSize(this.socketBufferSize);
    socket.setSendBufferSize(this.socketBufferSize);
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(soTimeoutMs);
    socket.connect(new InetSocketAddress(dest.getHost(), dest.getPort()));

    recordSocketCreation(dest, socket);

    return new SocketAndStreams(socket);
}

From source file:org.jsnap.request.SSLSocketFactory.java

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpParams params)
        throws IOException {
    if (sf == null)
        throw new IOException("SSLSocketFactory is not properly initialized");
    Socket s = sf.createSocket(host, port, localAddress, localPort);
    if (params != null) {
        int timeout = HttpConnectionParams.getConnectionTimeout(params);
        if (timeout != 0)
            s.setSoTimeout(timeout);
    }// w  w w.  ja  v a 2  s  .co m
    return s;
}

From source file:com.jivesoftware.os.jive.utils.http.client.CustomSecureProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException {

    Socket socket = sslSocketFactory.createSocket();

    if (localAddress != null && port > 0) {
        socket.bind(new InetSocketAddress(localAddress, localPort));
    }//from ww  w.j  ava 2  s  .  c  om

    int timeout = params.getSoTimeout();
    if (timeout > 0) {
        socket.setSoTimeout(timeout);
    }

    socket.connect(new InetSocketAddress(host, port), params.getConnectionTimeout());

    return socket;
}