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

The following examples show how to use java.net.Socket#setSoLinger() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@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 2
public void connect(int connectTimeout) {
    try {
        clientSocket = new Socket();

        clientSocket.connect(new InetSocketAddress(mllpHost, mllpPort), connectTimeout);

        clientSocket.setSoTimeout(soTimeout);
        clientSocket.setSoLinger(false, -1);
        clientSocket.setReuseAddress(reuseAddress);
        clientSocket.setTcpNoDelay(tcpNoDelay);

        inputStream = clientSocket.getInputStream();
        outputStream = new BufferedOutputStream(clientSocket.getOutputStream(), 2048);
    } catch (IOException e) {
        String errorMessage = String.format("Unable to establish connection to %s:%s", mllpHost, mllpPort);
        log.error(errorMessage, e);
        throw new MllpJUnitResourceException(errorMessage, e);
    }
}
 
Example 3
@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 4
@Override
public void run() {
    while (!isTerminated()) {
        try {
            Socket conn = socket.accept();
            conn.setSoLinger(true, 60);
            connectionThreads.execute(new ConnectionHandler(getOwner(), conn));
        } catch (IOException e) {
            if (!isTerminated()) {
                owner.forceStop(e);
            }
        }
    }
}
 
Example 5
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 6
@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 7
Source Project: jlibs   File: TCPConnection.java    License: Apache License 2.0 5 votes vote down vote up
protected void init() throws IOException{
    uniqueID = (server==null ? "C" : "A")+id;
    Socket socket = selectable.socket();
    if(TCP_NODELAY!=null)
        socket.setTcpNoDelay(TCP_NODELAY);
    if(SO_LINGER!=null)
        socket.setSoLinger(SO_LINGER<0, SO_LINGER);
    if(SO_SNDBUF!=null)
        socket.setSendBufferSize(SO_SNDBUF);
    if(SO_RCVBUF!=null)
        socket.setReceiveBufferSize(SO_RCVBUF);
}
 
Example 8
Source Project: jdk8u_jdk   File: Race.java    License: GNU General Public License v2.0 5 votes vote down vote up
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++) {
            try {
                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();
                }
            } catch (ConnectException e) {
                System.err.println("Exception " + e + " Port: " + port);
            }
        }
    }
}
 
Example 9
private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress)
    throws IOException {
  socketChannel_ = socketChannel;
  socketAddress_ = socketAddress;

  // make it a nonblocking channel
  socketChannel.configureBlocking(false);

  // set options
  Socket socket = socketChannel.socket();
  socket.setSoLinger(false, 0);
  socket.setTcpNoDelay(true);
  setTimeout(timeout);
}
 
Example 10
Source Project: openjdk-jdk8u   File: Race.java    License: GNU General Public License v2.0 5 votes vote down vote up
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++) {
            try {
                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();
                }
            } catch (ConnectException e) {
                System.err.println("Exception " + e + " Port: " + port);
            }
        }
    }
}
 
Example 11
Source Project: drift   File: ApacheThriftMethodInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private void setSocketProperties(Socket socket)
        throws SocketException
{
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setSoTimeout(Ints.saturatedCast(requestTimeoutMillis));
}
 
Example 12
private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress)
    throws IOException {
  socketChannel_ = socketChannel;
  socketAddress_ = socketAddress;

  // make it a nonblocking channel
  socketChannel.configureBlocking(false);

  // set options
  Socket socket = socketChannel.socket();
  socket.setSoLinger(false, 0);
  socket.setTcpNoDelay(true);
  setTimeout(timeout);
}
 
Example 13
Source Project: tomcatsrc   File: BioSender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 14
Source Project: Tomcat7.0.67   File: BioSender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 15
Source Project: incubator-retired-blur   File: TSocket.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the socket object
 */
private void initSocket() {
  socket_ = new Socket();
  try {
    socket_.setSoLinger(false, 0);
    socket_.setTcpNoDelay(true);
    socket_.setSoTimeout(timeout_);
  } catch (SocketException sx) {
    LOGGER.error("Could not configure socket.", sx);
  }
}
 
Example 16
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
Source Project: hottub   File: Race.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 18
Source Project: nettythrift   File: HTTPUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static void configSocket(Socket socket) throws SocketException {
    /**
     * 设置Socket属性
     */
    // true表示关闭Socket的缓冲,立即发送数据..其默认值为false
    // 若Socket的底层实现不支持TCP_NODELAY选项,则会抛出SocketException
    socket.setTcpNoDelay(true);
    // 表示是否允许重用Socket所绑定的本地地址
    socket.setReuseAddress(true);
    // 表示接收数据时的等待超时时间,单位毫秒..其默认值为0,表示会无限等待,永远不会超时
    // 当通过Socket的输入流读数据时,如果还没有数据,就会等待
    // 超时后会抛出SocketTimeoutException,且抛出该异常后Socket仍然是连接的,可以尝试再次读数据
    socket.setSoTimeout(5000);
    // 表示当执行Socket.close()时,是否立即关闭底层的Socket
    // 这里设置为当Socket关闭后,底层Socket延迟5秒后再关闭,而5秒后所有未发送完的剩余数据也会被丢弃
    // 默认情况下,执行Socket.close()方法,该方法会立即返回,但底层的Socket实际上并不立即关闭
    // 它会延迟一段时间,直到发送完所有剩余的数据,才会真正关闭Socket,断开连接
    // Tips:当程序通过输出流写数据时,仅仅表示程序向网络提交了一批数据,由网络负责输送到接收方
    // Tips:当程序关闭Socket,有可能这批数据还在网络上传输,还未到达接收方
    // Tips:这里所说的"未发送完的剩余数据"就是指这种还在网络上传输,未被接收方接收的数据
    socket.setSoLinger(true, 5);
    // 表示发送数据的缓冲区的大小
    socket.setSendBufferSize(1024);
    // 表示接收数据的缓冲区的大小
    socket.setReceiveBufferSize(1024);
    // 表示对于长时间处于空闲状态(连接的两端没有互相传送数据)的Socket,是否要自动把它关闭,true为是
    // 其默认值为false,表示TCP不会监视连接是否有效,不活动的客户端可能会永久存在下去,而不会注意到服务器已经崩溃
    socket.setKeepAlive(true);
    // 表示是否支持发送一个字节的TCP紧急数据,socket.sendUrgentData(data)用于发送一个字节的TCP紧急数据
    // 其默认为false,即接收方收到紧急数据时不作任何处理,直接将其丢弃..若用户希望发送紧急数据,则应设其为true
    // 设为true后,接收方会把收到的紧急数据与普通数据放在同样的队列中
    socket.setOOBInline(true);
    // 该方法用于设置服务类型,以下代码请求高可靠性和最小延迟传输服务(把0x04与0x10进行位或运算)
    // Socket类用4个整数表示服务类型
    // 0x02:低成本(二进制的倒数第二位为1)
    // 0x04:高可靠性(二进制的倒数第三位为1)
    // 0x08:最高吞吐量(二进制的倒数第四位为1)
    // 0x10:最小延迟(二进制的倒数第五位为1)
    socket.setTrafficClass(0x04 | 0x10);
    // 该方法用于设定连接时间,延迟,带宽的相对重要性(该方法的三个参数表示网络传输数据的3项指标)
    // connectionTime--该参数表示用最少时间建立连接
    // latency---------该参数表示最小延迟
    // bandwidth-------该参数表示最高带宽
    // 可以为这些参数赋予任意整数值,这些整数之间的相对大小就决定了相应参数的相对重要性
    // 如这里设置的就是---最高带宽最重要,其次是最小连接时间,最后是最小延迟
    socket.setPerformancePreferences(2, 1, 3);
}
 
Example 19
private static Socket createSocket(final String host, final int port, final Options options)
    throws SQLException {
  Socket socket;
  try {
    socket = Utils.createSocket(options, host);
    socket.setTcpNoDelay(options.tcpNoDelay);

    if (options.socketTimeout != null) {
      socket.setSoTimeout(options.socketTimeout);
    }
    if (options.tcpKeepAlive) {
      socket.setKeepAlive(true);
    }
    if (options.tcpRcvBuf != null) {
      socket.setReceiveBufferSize(options.tcpRcvBuf);
    }
    if (options.tcpSndBuf != null) {
      socket.setSendBufferSize(options.tcpSndBuf);
    }
    if (options.tcpAbortiveClose) {
      socket.setSoLinger(true, 0);
    }

    // Bind the socket to a particular interface if the connection property
    // localSocketAddress has been defined.
    if (options.localSocketAddress != null) {
      InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
      socket.bind(localAddress);
    }

    if (!socket.isConnected()) {
      InetSocketAddress sockAddr =
          options.pipe == null ? new InetSocketAddress(host, port) : null;
      socket.connect(sockAddr, options.connectTimeout);
    }
    return socket;

  } catch (IOException ioe) {
    throw ExceptionFactory.INSTANCE.create(
        String.format(
            "Socket fail to connect to host:%s, port:%s. %s", host, port, ioe.getMessage()),
        "08000",
        ioe);
  }
}
 
Example 20
/**
 * Creates a socket and connects it to the given host for a communication
 * channel. Socket timeouts are automatically set according to the values of
 * {@link FTPConnector#connectionTimeout}, {@link FTPConnector#readTimeout}
 * and {@link FTPConnector#closeTimeout}.
 * 
 * If you are extending FTPConnector, consider using this method to
 * establish your socket connection for the communication channel, instead
 * of creating Socket objects, since it is already aware of the timeout
 * values possibly given by the caller. Moreover the caller can abort
 * connection calling {@link FTPClient#abortCurrentConnectionAttempt()}.
 * 
 * @param host
 *            The host for the connection.
 * @param port
 *            The port for the connection.
 * @return The connected socket.
 * @throws IOException
 *             If connection fails.
 * @since 1.7
 */
protected Socket tcpConnectForCommunicationChannel(String host, int port) throws IOException {
	try {
		connectingCommunicationChannelSocket = new Socket();
		connectingCommunicationChannelSocket.setKeepAlive(true);
		connectingCommunicationChannelSocket.setSoTimeout(readTimeout * 1000);
		connectingCommunicationChannelSocket.setSoLinger(true, closeTimeout);
		connectingCommunicationChannelSocket.connect(new InetSocketAddress(host, port), connectionTimeout * 1000);
		return connectingCommunicationChannelSocket;
	} finally {
		connectingCommunicationChannelSocket = null;
	}
}