1. public int getSoLinger() throws SocketException {
    2. if (isClosed())
    3. throw new SocketException("Socket is closed");
    4. Object o = getImpl().getOption(SocketOptions.SO_LINGER);
    5. if (o instanceof Integer) {
    6. return ((Integer) o).intValue();
    7. } else {
    8. return -1;
    9. }
    10. }
    1. public void setSoLinger(boolean on, int linger) throws SocketException {
    2. if (isClosed())
    3. throw new SocketException("Socket is closed");
    4. if (!on) {
    5. getImpl().setOption(SocketOptions.SO_LINGER, new Boolean(on));
    6. } else {
    7. if (linger < 0) {
    8. throw new IllegalArgumentException("invalid value for SO_LINGER");
    9. }
    10. if (linger > 65535)
    11. linger = 65535;
    12. getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
    13. }
    14. }
    1. /**
    2. * Specify a linger-on-close timeout. This option disables/enables
    3. * immediate return from a <B>close()</B> of a TCP Socket. Enabling
    4. * this option with a non-zero Integer <I>timeout</I> means that a
    5. * <B>close()</B> will block pending the transmission and acknowledgement
    6. * of all data written to the peer, at which point the socket is closed
    7. * <I>gracefully</I>. Upon reaching the linger timeout, the socket is
    8. * closed <I>forcefully</I>, with a TCP RST. Enabling the option with a
    9. * timeout of zero does a forceful close immediately. If the specified
    10. * timeout value exceeds 65,535 it will be reduced to 65,535.
    11. * <P>
    12. * Valid only for TCP: SocketImpl
    13. *
    14. * @see Socket#setSoLinger
    15. * @see Socket#getSoLinger
    16. */
    17. @Native public final static int SO_LINGER = 0x0080;

    在Java Socket中,当我们调用Socket的close方法时,默认的行为是当底层网卡所有数据都发送完毕后,关闭连接
    通过setSoLinger方法,我们可以修改close方法的行为

    1. setSoLinger(true, 0)
      1. 当网卡收到关闭连接请求后,无论数据是否发送完毕,立即发送RST包关闭连接
    2. setSoLinger(true, delay_time)

    当网卡收到关闭连接请求后,等待delay_time
    如果在delay_time过程中数据发送完毕,正常四次挥手关闭连接
    如果在delay_time过程中数据没有发送完毕,发送RST包关闭连接