Java Code Examples for java.net.Socket.setSoLinger()

The following are Jave code examples for showing how to use setSoLinger() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: DefaultHttpServerConnection.java   View Source Code Vote up 7 votes
@Override
public void bind(final Socket socket, final HttpParams params) throws IOException {
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    assertNotOpen();
    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.setKeepAlive(HttpConnectionParams.getSoKeepalive(params));

    int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    super.bind(socket, params);
}
 
Example 2
Project: feeyo-redisproxy   File: JedisConnection.java   View Source Code Vote up 6 votes
public void connect() {

		if (!isConnected()) {

			try {
				socket = new Socket();
				socket.setReuseAddress(true);
				socket.setKeepAlive(true);
				socket.setTcpNoDelay(true);
				socket.setSoLinger(true, 0);
				
				socket.connect(new InetSocketAddress(host, port), connectionTimeout);
				if ( soTimeout > 0)
		          socket.setSoTimeout(soTimeout);
		        
		        outputStream = new RedisOutputStream(socket.getOutputStream());
		        inputStream = new RedisInputStream(socket.getInputStream());
		        
			} catch (IOException ex) {
				broken = true;
				throw new JedisConnectionException("Failed connecting to host " + host + ":" + port, ex);
			}
		}
	}
 
Example 3
Project: tomcat7   File: SocketProperties.java   View Source Code Vote up 6 votes
public void setProperties(Socket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (txBufSize != null)
        socket.setSendBufferSize(txBufSize.intValue());
    if (ooBInline !=null)
        socket.setOOBInline(ooBInline.booleanValue());
    if (soKeepAlive != null)
        socket.setKeepAlive(soKeepAlive.booleanValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soLingerOn != null && soLingerTime != null)
        socket.setSoLinger(soLingerOn.booleanValue(),
                soLingerTime.intValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
    if (tcpNoDelay != null)
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
 
Example 4
Project: lams   File: DefaultHttpClientConnection.java   View Source Code Vote up 6 votes
@Override
public void bind(
        final Socket socket,
        final HttpParams params) throws IOException {
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    assertNotOpen();
    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.setKeepAlive(HttpConnectionParams.getSoKeepalive(params));

    int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    super.bind(socket, params);
}
 
Example 5
Project: FirefoxData-android   File: DefaultHttpClientConnection.java   View Source Code Vote up 6 votes
@Override
public void bind(
        final Socket socket,
        final HttpParams params) throws IOException {
    Args.notNull(socket, "Socket");
    Args.notNull(params, "HTTP parameters");
    assertNotOpen();
    socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true));
    socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
    socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false));
    final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    super.bind(socket, params);
}
 
Example 6
Project: FirefoxData-android   File: DefaultHttpServerConnection.java   View Source Code Vote up 6 votes
@Override
public void bind(final Socket socket, final HttpParams params) throws IOException {
    Args.notNull(socket, "Socket");
    Args.notNull(params, "HTTP parameters");
    assertNotOpen();
    socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true));
    socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
    socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false));
    final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    super.bind(socket, params);
}
 
Example 7
Project: cyberduck   File: DefaultSocketConfigurator.java   View Source Code Vote up 6 votes
@Override
public void configure(final Socket socket) throws IOException {
    if(preferences.getInteger("connection.buffer.receive") > 0) {
        socket.setReceiveBufferSize(preferences.getInteger("connection.buffer.receive"));
    }
    if(preferences.getInteger("connection.buffer.send") > 0) {
        socket.setSendBufferSize(preferences.getInteger("connection.buffer.send"));
    }
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    if(log.isInfoEnabled()) {
        log.info(String.format("Set timeout to %dms for socket %s", timeout, socket));
    }
    socket.setSoTimeout(timeout);
    if(preferences.getBoolean("connection.socket.linger")) {
        // The setting only affects socket close. Make sure closing SSL socket does not hang because close_notify cannot be sent.
        socket.setSoLinger(true, timeout);
    }
    if(preferences.getBoolean("connection.socket.keepalive")) {
        socket.setKeepAlive(true);
    }
}
 
Example 8
Project: x7   File: Connection.java   View Source Code Vote up 6 votes
public void connect() {
  if (!isConnected()) {
    try {
      socket = new Socket();
      // ->@wjw_add
      socket.setReuseAddress(true);
      socket.setKeepAlive(true); // Will monitor the TCP connection is
      // valid
      socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
      // ensure timely delivery of data
      socket.setSoLinger(true, 0); // Control calls close () method,
      // the underlying socket is closed
      // immediately
      // <[email protected]_add

      socket.connect(new InetSocketAddress(host, port), connectionTimeout);
      socket.setSoTimeout(soTimeout);
      outputStream = new RedisOutputStream(socket.getOutputStream());
      inputStream = new RedisInputStream(socket.getInputStream());
    } catch (IOException ex) {
      broken = true;
      throw new JedisConnectionException(ex);
    }
  }
}
 
Example 9
Project: java-android-websocket-client   File: RequestListener.java   View Source Code Vote up 6 votes
@Override
public void run() {
    try {
        while (!isTerminated() && !Thread.interrupted()) {
            final Socket socket = this.serversocket.accept();
            socket.setSoTimeout(this.socketConfig.getSoTimeout());
            socket.setKeepAlive(this.socketConfig.isSoKeepAlive());
            socket.setTcpNoDelay(this.socketConfig.isTcpNoDelay());
            if (this.socketConfig.getRcvBufSize() > 0) {
                socket.setReceiveBufferSize(this.socketConfig.getRcvBufSize());
            }
            if (this.socketConfig.getSndBufSize() > 0) {
                socket.setSendBufferSize(this.socketConfig.getSndBufSize());
            }
            if (this.socketConfig.getSoLinger() >= 0) {
                socket.setSoLinger(true, this.socketConfig.getSoLinger());
            }
            final HttpServerConnection conn = this.connectionFactory.createConnection(socket);
            final Worker worker = new Worker(this.httpService, conn, this.exceptionLogger);
            this.executorService.execute(worker);
        }
    } catch (final Exception ex) {
        this.exceptionLogger.log(ex);
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: SocketProperties.java   View Source Code Vote up 6 votes
public void setProperties(Socket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (txBufSize != null)
        socket.setSendBufferSize(txBufSize.intValue());
    if (ooBInline !=null)
        socket.setOOBInline(ooBInline.booleanValue());
    if (soKeepAlive != null)
        socket.setKeepAlive(soKeepAlive.booleanValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soLingerOn != null && soLingerTime != null)
        socket.setSoLinger(soLingerOn.booleanValue(),
                soLingerTime.intValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
    if (tcpNoDelay != null)
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
 
Example 11
Project: drift   File: ApacheThriftMethodInvoker.java   View Source Code Vote up 5 votes
private void setSocketProperties(Socket socket)
        throws SocketException
{
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setSoTimeout(Ints.saturatedCast(requestTimeoutMillis));
}
 
Example 12
Project: tomcat7   File: BioSender.java   View Source Code Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled
 * is socket open return directly
 */
protected void openSocket() throws IOException {
   if(isConnected()) return ;
   try {
       socket = new Socket();
       InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
       socket.connect(sockaddr,(int)getTimeout());
       socket.setSendBufferSize(getTxBufSize());
       socket.setReceiveBufferSize(getRxBufSize());
       socket.setSoTimeout( (int) getTimeout());
       socket.setTcpNoDelay(getTcpNoDelay());
       socket.setKeepAlive(getSoKeepAlive());
       socket.setReuseAddress(getSoReuseAddress());
       socket.setOOBInline(getOoBInline());
       socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
       socket.setTrafficClass(getSoTrafficClass());
       setConnected(true);
       soOut = socket.getOutputStream();
       soIn  = socket.getInputStream();
       setRequestCount(0);
       setConnectTime(System.currentTimeMillis());
       if (log.isDebugEnabled())
           log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)));
  } catch (IOException ex1) {
      SenderState.getSenderState(getDestination()).setSuspect();
      if (log.isDebugEnabled())
          log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
      throw (ex1);
    }
    
 }
 
Example 13
Project: lams   File: DefaultClientConnectionOperator.java   View Source Code Vote up 5 votes
/**
 * 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
 */
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);
    }
}
 
Example 14
Project: lams   File: JIoEndpoint.java   View Source Code Vote up 5 votes
/**
 * Set the options for the current socket.
 */
protected boolean setSocketOptions(Socket socket) {
    // Process the connection
    int step = 1;
    try {

        // 1: Set socket options: timeout, linger, etc
        if (soLinger >= 0) { 
            socket.setSoLinger(true, soLinger);
        }
        if (tcpNoDelay) {
            socket.setTcpNoDelay(tcpNoDelay);
        }
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }

        // 2: SSL handshake
        step = 2;
        serverSocketFactory.handshake(socket);

    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            if (step == 2) {
                log.debug(sm.getString("endpoint.err.handshake"), t);
            } else {
                log.debug(sm.getString("endpoint.err.unexpected"), t);
            }
        }
        // Tell to close the socket
        return false;
    }
    return true;
}
 
Example 15
Project: lighthouse   File: BHttpConnectionBase.java   View Source Code Vote up 5 votes
@Override
public void shutdown() throws IOException {
    final Socket socket = this.socketHolder.getAndSet(null);
    if (socket != null) {
        // force abortive close (RST)
        try {
            socket.setSoLinger(true, 0);
        } catch (final IOException ex) {
        } finally {
            socket.close();
        }
    }
}
 
Example 16
Project: openjdk-jdk10   File: Race.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();
        final Phaser phaser = new Phaser(THREADS + 1);
        for (int i=0; i<100; i++) {
            final Socket s = new Socket("localhost", port);
            s.setSoLinger(false, 0);
            try (Socket sa = ss.accept()) {
                sa.setSoLinger(false, 0);
                final InputStream is = s.getInputStream();
                Thread[] threads = new Thread[THREADS];
                for (int j=0; j<THREADS; j++) {
                    threads[j] = new Thread() {
                    public void run() {
                        try {
                            phaser.arriveAndAwaitAdvance();
                            while (is.read() != -1)
                                Thread.sleep(50);
                        } catch (Exception x) {
                            if (!(x instanceof SocketException
                                  && x.getMessage().equalsIgnoreCase("socket closed")))
                                x.printStackTrace();
                            // ok, expect Socket closed
                        }
                    }};
                }
                for (int j=0; j<100; j++)
                    threads[j].start();
                phaser.arriveAndAwaitAdvance();
                s.close();
                for (int j=0; j<100; j++)
                    threads[j].join();
            }
        }
    }
}
 
Example 17
Project: lazycat   File: BioSender.java   View Source Code Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled is socket
 * open return directly
 */
protected void openSocket() throws IOException {
	if (isConnected())
		return;
	try {
		socket = new Socket();
		InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
		socket.connect(sockaddr, (int) getTimeout());
		socket.setSendBufferSize(getTxBufSize());
		socket.setReceiveBufferSize(getRxBufSize());
		socket.setSoTimeout((int) getTimeout());
		socket.setTcpNoDelay(getTcpNoDelay());
		socket.setKeepAlive(getSoKeepAlive());
		socket.setReuseAddress(getSoReuseAddress());
		socket.setOOBInline(getOoBInline());
		socket.setSoLinger(getSoLingerOn(), getSoLingerTime());
		socket.setTrafficClass(getSoTrafficClass());
		setConnected(true);
		soOut = socket.getOutputStream();
		soIn = socket.getInputStream();
		setRequestCount(0);
		setConnectTime(System.currentTimeMillis());
		if (log.isDebugEnabled())
			log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(),
					Integer.valueOf(getPort()), Long.valueOf(0)));
	} catch (IOException ex1) {
		SenderState.getSenderState(getDestination()).setSuspect();
		if (log.isDebugEnabled())
			log.debug(sm.getString("IDataSender.openSocket.failure", getAddress().getHostAddress(),
					Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
		throw (ex1);
	}

}
 
Example 18
Project: jdk8u-jdk   File: Race.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();
        final Phaser phaser = new Phaser(THREADS + 1);
        for (int i=0; i<100; i++) {
            final Socket s = new Socket("localhost", port);
            s.setSoLinger(false, 0);
            try (Socket sa = ss.accept()) {
                sa.setSoLinger(false, 0);
                final InputStream is = s.getInputStream();
                Thread[] threads = new Thread[THREADS];
                for (int j=0; j<THREADS; j++) {
                    threads[j] = new Thread() {
                    public void run() {
                        try {
                            phaser.arriveAndAwaitAdvance();
                            while (is.read() != -1)
                                Thread.sleep(50);
                        } catch (Exception x) {
                            if (!(x instanceof SocketException
                                  && x.getMessage().equalsIgnoreCase("socket closed")))
                                x.printStackTrace();
                            // ok, expect Socket closed
                        }
                    }};
                }
                for (int j=0; j<100; j++)
                    threads[j].start();
                phaser.arriveAndAwaitAdvance();
                s.close();
                for (int j=0; j<100; j++)
                    threads[j].join();
            }
        }
    }
}
 
Example 19
Project: java-android-websocket-client   File: BasicConnFactory.java   View Source Code Vote up 5 votes
@Override
public HttpClientConnection create(final HttpHost host) throws IOException {
    final String scheme = host.getSchemeName();
    Socket socket = null;
    if ("http".equalsIgnoreCase(scheme)) {
        socket = this.plainfactory != null ? this.plainfactory.createSocket() :
                new Socket();
    } if ("https".equalsIgnoreCase(scheme)) {
        socket = (this.sslfactory != null ? this.sslfactory :
                SSLSocketFactory.getDefault()).createSocket();
    }
    if (socket == null) {
        throw new IOException(scheme + " scheme is not supported");
    }
    final String hostname = host.getHostName();
    int port = host.getPort();
    if (port == -1) {
        if (host.getSchemeName().equalsIgnoreCase("http")) {
            port = 80;
        } else if (host.getSchemeName().equalsIgnoreCase("https")) {
            port = 443;
        }
    }
    socket.setSoTimeout(this.sconfig.getSoTimeout());
    if (this.sconfig.getSndBufSize() > 0) {
        socket.setSendBufferSize(this.sconfig.getSndBufSize());
    }
    if (this.sconfig.getRcvBufSize() > 0) {
        socket.setReceiveBufferSize(this.sconfig.getRcvBufSize());
    }
    socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
    final int linger = this.sconfig.getSoLinger();
    if (linger >= 0) {
        socket.setSoLinger(true, linger);
    }
    socket.setKeepAlive(this.sconfig.isSoKeepAlive());
    socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
    return this.connFactory.createConnection(socket);
}
 
Example 20
Project: java-android-websocket-client   File: BHttpConnectionBase.java   View Source Code Vote up 5 votes
@Override
public void shutdown() throws IOException {
    final Socket socket = this.socketHolder.getAndSet(null);
    if (socket != null) {
        // force abortive close (RST)
        try {
            socket.setSoLinger(true, 0);
        } catch (final IOException ex) {
        } finally {
            socket.close();
        }
    }
}