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:org.apache.http2.impl.conn.DefaultClientConnectionOperator.java

/**
 * Performs standard initializations on a newly created socket.
 *
 * @param sock      the socket to prepare
 * @param context   the context for the connection
 * @param params    the parameters from which to prepare the socket
 *
 * @throws IOException      in case of an IO problem
 *///from  w ww .  ja  v a 2s .  c o  m
protected void prepareSocket(final Socket sock, final HttpContext context, final HttpParams params)
        throws IOException {
    sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

    int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        sock.setSoLinger(linger > 0, linger);
    }
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Sets socket attributes on the socket.
 * @param socket The socket./*from   www  .  j  ava  2 s  .c  o  m*/
 * @throws SocketException
 */
protected void setSocketAttributes(Socket socket) throws SocketException {
    if (this.soTimeout >= 0) {
        socket.setSoTimeout(this.soTimeout);
    }
    if (this.soSendBufferSize > 0) {
        socket.setSendBufferSize(this.soSendBufferSize);
    }
    if (this.soReceiveBufferSize > 0) {
        socket.setReceiveBufferSize(this.soReceiveBufferSize);
    }
    socket.setTcpNoDelay(this.soTcpNoDelay);
    if (this.soLinger >= 0) {
        socket.setSoLinger(true, this.soLinger);
    }
    if (this.soTrafficClass >= 0) {
        socket.setTrafficClass(this.soTrafficClass);
    }
    socket.setKeepAlive(this.soKeepAlive);
}

From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from   w w  w .  j a  va  2 s . co m
 * 
 * @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 {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    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);
    verifyPeerIdentity(host, port, socket);
    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;/*from w  w w .  j a  v  a 2  s.c om*/
    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:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams httpConnectionParams)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (httpConnectionParams == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but HTTP connection parameters is null");
        throw new IllegalArgumentException("HTTP connection parameters cannot be null");
    }/*from   w  ww  . j a  va2 s . c  o m*/

    Socket socket = getSslContext().getSocketFactory().createSocket();
    SocketAddress localSocketAddress = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteSocketAddress = new InetSocketAddress(host, port);

    socket.setSoTimeout(httpConnectionParams.getSoTimeout());
    if (httpConnectionParams.getLinger() > 0) {
        socket.setSoLinger(true, httpConnectionParams.getLinger());
    } else {
        socket.setSoLinger(false, 0);
    }
    socket.setTcpNoDelay(httpConnectionParams.getTcpNoDelay());
    if (httpConnectionParams.getSendBufferSize() >= 0) {
        socket.setSendBufferSize(httpConnectionParams.getSendBufferSize());
    }
    if (httpConnectionParams.getReceiveBufferSize() >= 0) {
        socket.setReceiveBufferSize(httpConnectionParams.getReceiveBufferSize());
    }

    socket.bind(localSocketAddress);
    socket.connect(remoteSocketAddress, httpConnectionParams.getConnectionTimeout());
    return socket;
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

@Override
public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params) throws IOException {
    checkArgument(remoteAddress != null, "Remote address may not be null");
    checkArgument(params != null, "HTTP parameters may not be null");

    Socket socket = sock != null ? sock : new Socket();
    if (localAddress != null) {
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);// w w w. j av  a  2s.  c o m
    }

    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.connect(remoteAddress, HttpConnectionParams.getConnectionTimeout(params));

    if (socket instanceof SSLSocket) {
        return socket;
    }

    return getSSLContext().getSocketFactory().createSocket(socket, remoteAddress.getHostName(),
            remoteAddress.getPort(), true);
}

From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

public void run() {
    ServerSocket serverSocket = null;
    Socket connectionSocket = null;
    try {//from www . j  av a 2s  .c o m
        log.info("Trying to bind to localhost on port " + Integer.toString(port) + "...");
        serverSocket = new ServerSocket(port);
        log.info("Running Simple WebServer!\n");
        connectionSocket = serverSocket.accept();
        connectionSocket.setSoTimeout(30000);
        //go in a infinite loop, wait for connections, process request, send response
        while (running) {
            log.info("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                BufferedReader input;
                if (!connectionSocket.isClosed()) {
                    InetAddress client = connectionSocket.getInetAddress();
                    log.info(client.getHostName() + " connected to server.\n");
                    input = new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset()));
                    if (input.ready()) {
                        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
                        httpHandler(input, output);
                    }
                }
                //Prepare a outputStream. This will be used sending back our response
                //(header + requested file) to the client.
            } catch (Exception e) { //catch any errors, and print them
                log.info("\nError:" + e.getMessage());
                running = false;
            }
        }
    } catch (Exception e) {
        log.error("\nFatal Error:" + e.getMessage());
        running = false;
    } finally {
        try {
            if (connectionSocket != null) {
                connectionSocket.close();
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error while shutting down server sockets", e);
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.SocketListener.java

/** Customize request from socket.
 * Derived versions of SocketListener may specialize this method
 * to customize the request with attributes of the socket used (eg
 * SSL session ids)./*from   w  w w . jav a2s  . c  om*/
 * This version resets the SoTimeout if it has been reduced due to
 * low resources.  Derived implementations should call
 * super.customizeRequest(socket,request) unless persistConnection
 * has also been overridden and not called.
 * @param request
 */
protected void customizeRequest(Socket socket, HttpRequest request) {
    try {
        if (request.getHttpConnection().isThrottled()) {
            socket.setSoTimeout(getMaxIdleTimeMs());
            request.getHttpConnection().setThrottled(false);
        }
    } catch (Exception e) {
        LogSupport.ignore(log, e);
    }
}

From source file:com.owncloud.android.oc_framework.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit./*www .j a  v a2 s .  co  m*/
  * 
  * @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 {
    Log.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    //logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

From source file:com.subgraph.vega.internal.http.proxy.VegaHttpServerConnection.java

public void bind(final Socket socket, final HttpParams params) throws IOException {
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }/*w w  w  .ja v a 2 s.  c  o  m*/
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }

    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

    int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }

    super.bind(socket, params);
}