Example usage for java.net Socket setSoLinger

List of usage examples for java.net Socket setSoLinger

Introduction

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

Prototype

public void setSoLinger(boolean on, int linger) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_LINGER SO_LINGER with the specified linger time in seconds.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket client = new Socket("google.com", 80);
    client.setSoLinger(true, 1000);
    System.out.println(client.getSoLinger());

    client.close();//w ww  .j  a  va2s .  com
}

From source file:com.impetus.client.cassandra.common.CassandraUtilities.java

/**
* 
* @param host/*from  w  w w  . j  a  v  a2s  . c o m*/
* @param port
* @return
*/
public static boolean verifyConnection(String host, int port) {
    Socket socket = null;
    try {
        socket = new Socket(host, port);
        socket.setReuseAddress(true);
        socket.setSoLinger(true, 0);
        boolean isConnected = socket.isConnected();
        return isConnected;
    } catch (UnknownHostException e) {
        logger.warn("{}:{} is still down", host, port);
        return false;
    } catch (IOException e) {
        logger.warn("{}:{} is still down", host, port);
        return false;
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            logger.warn("{}:{} is still down", host, port);
        }
    }
}

From source file:net.oneandone.sushi.fs.webdav.WebdavConnection.java

public static WebdavConnection open(Socket socket, HttpParams params) throws IOException {
    int linger;/*from w  ww .j a v  a2s. co  m*/
    int buffersize;
    SessionInputBuffer input;
    SessionOutputBuffer output;

    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    buffersize = HttpConnectionParams.getSocketBufferSize(params);
    if (WebdavFilesystem.WIRE.isLoggable(Level.FINE)) {
        input = new LoggingSessionInputBuffer(socket, buffersize, params, WebdavFilesystem.WIRE);
        output = new LoggingSessionOutputBuffer(socket, buffersize, params, WebdavFilesystem.WIRE);
    } else {
        input = new SocketInputBuffer(socket, buffersize, params);
        output = new SocketOutputBuffer(socket, buffersize, params);
    }
    return new WebdavConnection(socket, input, output, params);
}

From source file:com.flipkart.phantom.thrift.impl.proxy.SocketObjectFactory.java

/**
 * Interface method implementation. Checks if the socket is open and then attempts to set Thrift specific socket properties.
 * An error in any of these operations will invalidate the specified Socket.
 * @see org.apache.commons.pool.PoolableObjectFactory#validateObject(Object)
 */// ww w  .j  a  va  2  s. c  o  m
public boolean validateObject(Socket socket) {
    if (socket.isClosed()) {
        return false;
    }
    try {
        socket.setSoLinger(false, 0);
        socket.setTcpNoDelay(true);
        return true;
    } catch (Exception e) {
        LOGGER.info("Socket is not valid for server : {} at port : {}", this.getThriftProxy().getThriftServer(),
                this.getThriftProxy().getThriftPort());
        return false;
    }
}

From source file:com.smartwork.client.gsocket.CommonSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ServerAddress address = (ServerAddress) key;
    Socket conn = new Socket();
    conn.setSoTimeout(networkConfig.getReadTimeout() * 1000);
    conn.setTcpNoDelay(networkConfig.isTcpNoDelay());
    conn.setReuseAddress(networkConfig.isReuseAddress());
    conn.setSoLinger(networkConfig.getSoLinger() > 0, networkConfig.getSoLinger());
    conn.setSendBufferSize(networkConfig.getSendBufferSize());
    conn.setReceiveBufferSize(networkConfig.getReceiveBufferSize());
    conn.connect(new InetSocketAddress(address.getHost(), address.getPort()),
            networkConfig.getConnectTimeout() * 1000);
    return conn;/*from  w ww. j a  va 2 s. c om*/
}

From source file:com.android.strictmodetest.StrictModeActivity.java

private void closeWithLinger(boolean linger) {
    Log.d(TAG, "Socket linger test; linger=" + linger);
    try {//from  w  ww  . jav a 2s . c  o  m
        Socket socket = new Socket();
        socket.setSoLinger(linger, 5);
        socket.close();
    } catch (IOException e) {
        Log.e(TAG, "Error with linger close", e);
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

/**
 * Configures socket with any options needed.
 * <p>//w w  w  . ja v a  2  s .  c om
 * Normally, the client using this factory would call {@link #createSocket(HttpContext)} and then configure the
 * socket. And indeed, it ({@link org.apache.http.impl.conn.DefaultHttpClientConnectionOperator}) does.
 * However, that socket is thrown away in {@link #connectSocket(int, Socket, HttpHost, InetSocketAddress,
 * InetSocketAddress, HttpContext)})
 * So apply here any configurations you actually want enabled.
 *
 * @param socket The socket to be configured
 * @throws SocketException
 */
private void configureSocket(Socket socket) throws SocketException {
    socket.setSoTimeout(SystemProperties.getClientProxyHttpClientTimeout());

    int linger = SystemProperties.getClientProxyHttpClientSoLinger();
    socket.setSoLinger(linger >= 0, linger);
}

From source file:com.qiniu.android.http.ClientConnectionOperator.java

/**
 * Performs standard initializations on a newly created socket.
 *
 * @param sock    the socket to prepare//w ww . j a  v  a 2s.  c  o  m
 * @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
 */
protected void prepareSocket(final Socket sock, final HttpContext context, final HttpParams params)
        throws IOException {
    sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

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

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 ww w  . j  a va 2  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.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");
    }//w w w.  j a  v a  2s.c o m
    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");
        }
    }
}