对一个的java类为java.net.SocketOptions
TCP_NODELAY
Fetch the local address binding of a socket (this option cannot be “set” only “gotten”, since sockets are bound at creation time, and so the locally bound address cannot be changed). The default local address of a socket is INADDR_ANY, meaning any local address on a multi-homed host. A multi-homed host can use this option to accept connections to only one of its addresses (in the case of a ServerSocket or DatagramSocket), or to specify its return address to the peer (for a Socket or DatagramSocket). The parameter of this option is an InetAddress.
This option must be specified in the constructor.
/**
* Disable Nagle's algorithm for this connection. Written data
* to the network is not buffered pending acknowledgement of
* previously written data.
*<P>
* Valid for TCP only: SocketImpl.
*
* @see Socket#setTcpNoDelay
* @see Socket#getTcpNoDelay
*/
@Native public final static int TCP_NODELAY = 0x0001;
设置TCP_NODELAY为true可确保包无论大小会尽可能快地发送。正常情况下,小数据包在发送前会组合为更大的包。另外,在发送另一个包之前,本地主机需要等待远程系统对前一个包的确认,这称为Nagle算法。Nagle算法的问题是,如果远程系统没有足够快的将确认发送会本地系统,那么依赖于小数据量信息稳定传输的应用程序会变得很慢,对于GUI程序,比如游戏或网络极端及应用程序(服务器需要实时跟踪客户端鼠标的移动)。这个问题尤其严重,在一个相当慢的网络中,即使简单地打字也会由于持续的缓冲而变得太慢。设置TCP_NODELAY为true可以打破这种缓冲模式,这样所有包一旦就绪就会发送。
SO_LINGER
/**
* Specify a linger-on-close timeout. This option disables/enables
* immediate return from a <B>close()</B> of a TCP Socket. Enabling
* this option with a non-zero Integer <I>timeout</I> means that a
* <B>close()</B> will block pending the transmission and acknowledgement
* of all data written to the peer, at which point the socket is closed
* <I>gracefully</I>. Upon reaching the linger timeout, the socket is
* closed <I>forcefully</I>, with a TCP RST. Enabling the option with a
* timeout of zero does a forceful close immediately. If the specified
* timeout value exceeds 65,535 it will be reduced to 65,535.
* <P>
* Valid only for TCP: SocketImpl
*
* @see Socket#setSoLinger
* @see Socket#getSoLinger
*/
@Native public final static int SO_LINGER = 0x0080;
SO_LINGER选项指定了Socket关闭时如何处理尚未发送的数据报。默认情况下,close方法将立刻返回,但系统仍会尝试发送剩余的数据,如果延迟时间设置为0,那么当Socket关闭时,所有未发送的数据包都将被丢弃。如果SO_LINGER打开而且延迟时间设置为任意整数,close方法会阻塞(阻塞时间为指定的秒数),等待发送数据和接收确认。当过去相应秒数后,Socket关闭,所有剩余的数据都不会发送,也不会收到确认。
如果底层Socket实现不支持SO_LINGER选项,setSoLinger和getSoLinger这两个方法都会抛出SocketException异常,如果试图将延迟时间设置为一个负数,setSoLinger方法还会抛出一个IllegalArgumentException异常。
/**
* Enable/disable {@link SocketOptions#SO_LINGER SO_LINGER} with the
* specified linger time in seconds. The maximum timeout value is platform
* specific.
*
* The setting only affects socket close.
*
* @param on whether or not to linger on.
* @param linger how long to linger for, if on is true.
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
* @exception IllegalArgumentException if the linger value is negative.
* @since JDK1.1
* @see #getSoLinger()
*/
public void setSoLinger(boolean on, int linger) throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!on) {
getImpl().setOption(SocketOptions.SO_LINGER, new Boolean(on));
} else {
if (linger < 0) {
throw new IllegalArgumentException("invalid value for SO_LINGER");
}
if (linger > 65535)
linger = 65535;
getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
}
}
不过,getSoLinger方法可以返回-1,指示这个选项被禁用,会根据需要用更多时间发送剩余的数据。
/**
* Returns setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
* -1 returns implies that the
* option is disabled.
*
* The setting only affects socket close.
*
* @return the setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
* @since JDK1.1
* @see #setSoLinger(boolean, int)
*/
public int getSoLinger() throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
Object o = getImpl().getOption(SocketOptions.SO_LINGER);
if (o instanceof Integer) {
return ((Integer) o).intValue();
} else {
return -1;
}
}
SO_RCVBUF和SO_SNDBUF
TCP使用缓冲区提升网络性能。较大的缓冲区会提升较高带宽(比如10Mb/s)的性能。而较慢的带宽利用较少的缓冲区会有更好的表现。一般来讲,传输连续的大数据块时(这在文件传输协议如FTP和HTTP中很常见),可以从大缓冲区受益;而对于交互式会话的小数据量传输(如Telnet和很多游戏),大缓冲区则没有多大帮助。一些相对较老的操作系统在小文件和慢速网络时代设计的,如BSD 4.2使用2KB字节的缓冲区,Windows XP使用17 520字节的缓冲区。如今,128KB字节已经是一个常见的默认设置。
可以达到的最大带宽等于缓冲区大小除以延迟。例如,在Windows XP上,假设两个主机之间的延迟为半秒(500ms),则带宽为17520字节/0.5秒=35040字节/秒=273.75kb/s。这就是Socket的最大速度。而不论网络速度有多块,这对于一个拨号连接来说相当快,对于ISDN也不错,不过对于DSL或FIOS就不够了。
可以通过减少延迟来提高速度,不够,延迟与网络硬件有关。另外还取决于你的应用控制之外的其他一些因素。另一方面,缓冲区的大小是可以控制的,例如,如果把缓冲区的大小从17520字节增加到128字节,最大带宽就会增加到2Mb/s。将缓冲区大小再次增加到256KB字节,那么最大带宽就会加倍到4Mb/s。当然,网络本身对最大带宽也有限制的,将缓冲区大小设置得过高,程序会试图以过高的速度发送和接收数据,而网络来不及处理,这就会导致拥塞、丢包和性能下降。因此,要得到最大带宽,需要让缓冲区大小与连接的延迟匹配,使她稍小于网络的带宽。
可以使用ping手动检查某个特定主机的延迟,或者可以在程序中测量InetAddress.isReachable调用的时间。
/**
* Set a hint the size of the underlying buffers used by the
* platform for outgoing network I/O. When used in set, this is a
* suggestion to the kernel from the application about the size of
* buffers to use for the data to be sent over the socket. When
* used in get, this must return the size of the buffer actually
* used by the platform when sending out data on this socket.
*
* Valid for all sockets: SocketImpl, DatagramSocketImpl
*
* @see Socket#setSendBufferSize
* @see Socket#getSendBufferSize
* @see DatagramSocket#setSendBufferSize
* @see DatagramSocket#getSendBufferSize
*/
@Native public final static int SO_SNDBUF = 0x1001;
/**
* Set a hint the size of the underlying buffers used by the
* platform for incoming network I/O. When used in set, this is a
* suggestion to the kernel from the application about the size of
* buffers to use for the data to be received over the
* socket. When used in get, this must return the size of the
* buffer actually used by the platform when receiving in data on
* this socket.
*
* Valid for all sockets: SocketImpl, DatagramSocketImpl
*
* @see Socket#setReceiveBufferSize
* @see Socket#getReceiveBufferSize
* @see DatagramSocket#setReceiveBufferSize
* @see DatagramSocket#getReceiveBufferSize
*/
@Native public final static int SO_RCVBUF = 0x1002;
SO_RCVBUF选项控制用于网络输入的建议的接收缓冲区大小。SO_SNDBUF选项控制用于网络输入的建议的发送缓冲区大小。尽管看起来可以单独设置发送和缓冲区大小,但实际上缓冲区通常会设置为二者中较小的一个,例如,如果将发送缓冲区设置为64KB,而接收缓冲区设置为128KB,那么发送和接收缓冲区的大小都将是64KB。Java的相关方法会返回接收缓冲区为128KB,但底层TCP栈实际上会使用64KB。
setReceiveBufferSize或者setSendBufferSize方法会对Socket上缓冲输出使用的字节数给出一个建议,不过,底层实现完全可以忽略或调整这个建议。具体的,UNIX和Linux系统通常指定一个最大缓冲区大小,一般是64KB或256KB,而且不允许任何Socket有更大的缓冲区。如果你试图设置一个更大的值,Java会把它调整为可能的最大缓冲区大小。在Linux上,底层实现由可能将请求的缓冲区大小加倍,这也并非没有先例。例如,如果你请求一个64KB缓冲区,可能会得到一个128KB的缓冲区。
一般来讲,如果你发现你的应用不能充分利用可用带宽(例如,你有一个25Mb/sd的网络连接,但是数据传输率仅仅为1.5Mb/s),那么可以试着增加缓冲区大小。相反,如果存在丢包和拥塞现象,则需要减少缓冲区大小。不过,大多数情况下, 除非网络在某个方向上负载过大, 否则默认值就很合适。具体来说,现在操作系统使用TCP滑动窗口来动态调整缓冲区大小,以适应网络。与几乎所有性能调优建议一样,一般经验是除非你检测到了某个问题,否则不要进行调整。即使非要调整,可以在操作系统级增加允许的最大缓冲区大小,与调整单个socket的缓冲区大小相比,前者可以得到更大的速度提升。
java.net.StandardSocketOptions
package java.net;
/**
* Defines the <em>standard</em> socket options.
*
* <p> The {@link SocketOption#name name} of each socket option defined by this
* class is its field name.
*
* <p> In this release, the socket options defined here are used by {@link
* java.nio.channels.NetworkChannel network} channels in the {@link
* java.nio.channels channels} package.
*
* @since 1.7
*/
public final class StandardSocketOptions {
private StandardSocketOptions() { }
// -- SOL_SOCKET --
/**
* Allow transmission of broadcast datagrams.
*
* <p> The value of this socket option is a {@code Boolean} that represents
* whether the option is enabled or disabled. The option is specific to
* datagram-oriented sockets sending to {@link java.net.Inet4Address IPv4}
* broadcast addresses. When the socket option is enabled then the socket
* can be used to send <em>broadcast datagrams</em>.
*
* <p> The initial value of this socket option is {@code FALSE}. The socket
* option may be enabled or disabled at any time. Some operating systems may
* require that the Java virtual machine be started with implementation
* specific privileges to enable this option or send broadcast datagrams.
*
* @see <a href="http://www.ietf.org/rfc/rfc919.txt">RFC 929:
* Broadcasting Internet Datagrams</a>
* @see DatagramSocket#setBroadcast
*/
public static final SocketOption<Boolean> SO_BROADCAST =
new StdSocketOption<Boolean>("SO_BROADCAST", Boolean.class);
/**
* Keep connection alive.
*
* <p> The value of this socket option is a {@code Boolean} that represents
* whether the option is enabled or disabled. When the {@code SO_KEEPALIVE}
* option is enabled the operating system may use a <em>keep-alive</em>
* mechanism to periodically probe the other end of a connection when the
* connection is otherwise idle. The exact semantics of the keep alive
* mechanism is system dependent and therefore unspecified.
*
* <p> The initial value of this socket option is {@code FALSE}. The socket
* option may be enabled or disabled at any time.
*
* @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122
* Requirements for Internet Hosts -- Communication Layers</a>
* @see Socket#setKeepAlive
*/
public static final SocketOption<Boolean> SO_KEEPALIVE =
new StdSocketOption<Boolean>("SO_KEEPALIVE", Boolean.class);
/**
* The size of the socket send buffer.
*
* <p> The value of this socket option is an {@code Integer} that is the
* size of the socket send buffer in bytes. The socket send buffer is an
* output buffer used by the networking implementation. It may need to be
* increased for high-volume connections. The value of the socket option is
* a <em>hint</em> to the implementation to size the buffer and the actual
* size may differ. The socket option can be queried to retrieve the actual
* size.
*
* <p> For datagram-oriented sockets, the size of the send buffer may limit
* the size of the datagrams that may be sent by the socket. Whether
* datagrams larger than the buffer size are sent or discarded is system
* dependent.
*
* <p> The initial/default size of the socket send buffer and the range of
* allowable values is system dependent although a negative size is not
* allowed. An attempt to set the socket send buffer to larger than its
* maximum size causes it to be set to its maximum size.
*
* <p> An implementation allows this socket option to be set before the
* socket is bound or connected. Whether an implementation allows the
* socket send buffer to be changed after the socket is bound is system
* dependent.
*
* @see Socket#setSendBufferSize
*/
public static final SocketOption<Integer> SO_SNDBUF =
new StdSocketOption<Integer>("SO_SNDBUF", Integer.class);
/**
* The size of the socket receive buffer.
*
* <p> The value of this socket option is an {@code Integer} that is the
* size of the socket receive buffer in bytes. The socket receive buffer is
* an input buffer used by the networking implementation. It may need to be
* increased for high-volume connections or decreased to limit the possible
* backlog of incoming data. The value of the socket option is a
* <em>hint</em> to the implementation to size the buffer and the actual
* size may differ.
*
* <p> For datagram-oriented sockets, the size of the receive buffer may
* limit the size of the datagrams that can be received. Whether datagrams
* larger than the buffer size can be received is system dependent.
* Increasing the socket receive buffer may be important for cases where
* datagrams arrive in bursts faster than they can be processed.
*
* <p> In the case of stream-oriented sockets and the TCP/IP protocol, the
* size of the socket receive buffer may be used when advertising the size
* of the TCP receive window to the remote peer.
*
* <p> The initial/default size of the socket receive buffer and the range
* of allowable values is system dependent although a negative size is not
* allowed. An attempt to set the socket receive buffer to larger than its
* maximum size causes it to be set to its maximum size.
*
* <p> An implementation allows this socket option to be set before the
* socket is bound or connected. Whether an implementation allows the
* socket receive buffer to be changed after the socket is bound is system
* dependent.
*
* @see <a href="http://www.ietf.org/rfc/rfc1323.txt">RFC 1323: TCP
* Extensions for High Performance</a>
* @see Socket#setReceiveBufferSize
* @see ServerSocket#setReceiveBufferSize
*/
public static final SocketOption<Integer> SO_RCVBUF =
new StdSocketOption<Integer>("SO_RCVBUF", Integer.class);
/**
* Re-use address.
*
* <p> The value of this socket option is a {@code Boolean} that represents
* whether the option is enabled or disabled. The exact semantics of this
* socket option are socket type and system dependent.
*
* <p> In the case of stream-oriented sockets, this socket option will
* usually determine whether the socket can be bound to a socket address
* when a previous connection involving that socket address is in the
* <em>TIME_WAIT</em> state. On implementations where the semantics differ,
* and the socket option is not required to be enabled in order to bind the
* socket when a previous connection is in this state, then the
* implementation may choose to ignore this option.
*
* <p> For datagram-oriented sockets the socket option is used to allow
* multiple programs bind to the same address. This option should be enabled
* when the socket is to be used for Internet Protocol (IP) multicasting.
*
* <p> An implementation allows this socket option to be set before the
* socket is bound or connected. Changing the value of this socket option
* after the socket is bound has no effect. The default value of this
* socket option is system dependent.
*
* @see <a href="http://www.ietf.org/rfc/rfc793.txt">RFC 793: Transmission
* Control Protocol</a>
* @see ServerSocket#setReuseAddress
*/
public static final SocketOption<Boolean> SO_REUSEADDR =
new StdSocketOption<Boolean>("SO_REUSEADDR", Boolean.class);
/**
* Linger on close if data is present.
*
* <p> The value of this socket option is an {@code Integer} that controls
* the action taken when unsent data is queued on the socket and a method
* to close the socket is invoked. If the value of the socket option is zero
* or greater, then it represents a timeout value, in seconds, known as the
* <em>linger interval</em>. The linger interval is the timeout for the
* {@code close} method to block while the operating system attempts to
* transmit the unsent data or it decides that it is unable to transmit the
* data. If the value of the socket option is less than zero then the option
* is disabled. In that case the {@code close} method does not wait until
* unsent data is transmitted; if possible the operating system will transmit
* any unsent data before the connection is closed.
*
* <p> This socket option is intended for use with sockets that are configured
* in {@link java.nio.channels.SelectableChannel#isBlocking() blocking} mode
* only. The behavior of the {@code close} method when this option is
* enabled on a non-blocking socket is not defined.
*
* <p> The initial value of this socket option is a negative value, meaning
* that the option is disabled. The option may be enabled, or the linger
* interval changed, at any time. The maximum value of the linger interval
* is system dependent. Setting the linger interval to a value that is
* greater than its maximum value causes the linger interval to be set to
* its maximum value.
*
* @see Socket#setSoLinger
*/
public static final SocketOption<Integer> SO_LINGER =
new StdSocketOption<Integer>("SO_LINGER", Integer.class);
// -- IPPROTO_IP --
/**
* The Type of Service (ToS) octet in the Internet Protocol (IP) header.
*
* <p> The value of this socket option is an {@code Integer} representing
* the value of the ToS octet in IP packets sent by sockets to an {@link
* StandardProtocolFamily#INET IPv4} socket. The interpretation of the ToS
* octet is network specific and is not defined by this class. Further
* information on the ToS octet can be found in <a
* href="http://www.ietf.org/rfc/rfc1349.txt">RFC 1349</a> and <a
* href="http://www.ietf.org/rfc/rfc2474.txt">RFC 2474</a>. The value
* of the socket option is a <em>hint</em>. An implementation may ignore the
* value, or ignore specific values.
*
* <p> The initial/default value of the TOS field in the ToS octet is
* implementation specific but will typically be {@code 0}. For
* datagram-oriented sockets the option may be configured at any time after
* the socket has been bound. The new value of the octet is used when sending
* subsequent datagrams. It is system dependent whether this option can be
* queried or changed prior to binding the socket.
*
* <p> The behavior of this socket option on a stream-oriented socket, or an
* {@link StandardProtocolFamily#INET6 IPv6} socket, is not defined in this
* release.
*
* @see DatagramSocket#setTrafficClass
*/
public static final SocketOption<Integer> IP_TOS =
new StdSocketOption<Integer>("IP_TOS", Integer.class);
/**
* The network interface for Internet Protocol (IP) multicast datagrams.
*
* <p> The value of this socket option is a {@link NetworkInterface} that
* represents the outgoing interface for multicast datagrams sent by the
* datagram-oriented socket. For {@link StandardProtocolFamily#INET6 IPv6}
* sockets then it is system dependent whether setting this option also
* sets the outgoing interface for multicast datagrams sent to IPv4
* addresses.
*
* <p> The initial/default value of this socket option may be {@code null}
* to indicate that outgoing interface will be selected by the operating
* system, typically based on the network routing tables. An implementation
* allows this socket option to be set after the socket is bound. Whether
* the socket option can be queried or changed prior to binding the socket
* is system dependent.
*
* @see java.nio.channels.MulticastChannel
* @see MulticastSocket#setInterface
*/
public static final SocketOption<NetworkInterface> IP_MULTICAST_IF =
new StdSocketOption<NetworkInterface>("IP_MULTICAST_IF", NetworkInterface.class);
/**
* The <em>time-to-live</em> for Internet Protocol (IP) multicast datagrams.
*
* <p> The value of this socket option is an {@code Integer} in the range
* {@code 0 <= value <= 255}. It is used to control the scope of multicast
* datagrams sent by the datagram-oriented socket.
* In the case of an {@link StandardProtocolFamily#INET IPv4} socket
* the option is the time-to-live (TTL) on multicast datagrams sent by the
* socket. Datagrams with a TTL of zero are not transmitted on the network
* but may be delivered locally. In the case of an {@link
* StandardProtocolFamily#INET6 IPv6} socket the option is the
* <em>hop limit</em> which is number of <em>hops</em> that the datagram can
* pass through before expiring on the network. For IPv6 sockets it is
* system dependent whether the option also sets the <em>time-to-live</em>
* on multicast datagrams sent to IPv4 addresses.
*
* <p> The initial/default value of the time-to-live setting is typically
* {@code 1}. An implementation allows this socket option to be set after
* the socket is bound. Whether the socket option can be queried or changed
* prior to binding the socket is system dependent.
*
* @see java.nio.channels.MulticastChannel
* @see MulticastSocket#setTimeToLive
*/
public static final SocketOption<Integer> IP_MULTICAST_TTL =
new StdSocketOption<Integer>("IP_MULTICAST_TTL", Integer.class);
/**
* Loopback for Internet Protocol (IP) multicast datagrams.
*
* <p> The value of this socket option is a {@code Boolean} that controls
* the <em>loopback</em> of multicast datagrams. The value of the socket
* option represents if the option is enabled or disabled.
*
* <p> The exact semantics of this socket options are system dependent.
* In particular, it is system dependent whether the loopback applies to
* multicast datagrams sent from the socket or received by the socket.
* For {@link StandardProtocolFamily#INET6 IPv6} sockets then it is
* system dependent whether the option also applies to multicast datagrams
* sent to IPv4 addresses.
*
* <p> The initial/default value of this socket option is {@code TRUE}. An
* implementation allows this socket option to be set after the socket is
* bound. Whether the socket option can be queried or changed prior to
* binding the socket is system dependent.
*
* @see java.nio.channels.MulticastChannel
* @see MulticastSocket#setLoopbackMode
*/
public static final SocketOption<Boolean> IP_MULTICAST_LOOP =
new StdSocketOption<Boolean>("IP_MULTICAST_LOOP", Boolean.class);
// -- IPPROTO_TCP --
/**
* Disable the Nagle algorithm.
*
* <p> The value of this socket option is a {@code Boolean} that represents
* whether the option is enabled or disabled. The socket option is specific to
* stream-oriented sockets using the TCP/IP protocol. TCP/IP uses an algorithm
* known as <em>The Nagle Algorithm</em> to coalesce short segments and
* improve network efficiency.
*
* <p> The default value of this socket option is {@code FALSE}. The
* socket option should only be enabled in cases where it is known that the
* coalescing impacts performance. The socket option may be enabled at any
* time. In other words, the Nagle Algorithm can be disabled. Once the option
* is enabled, it is system dependent whether it can be subsequently
* disabled. If it cannot, then invoking the {@code setOption} method to
* disable the option has no effect.
*
* @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122:
* Requirements for Internet Hosts -- Communication Layers</a>
* @see Socket#setTcpNoDelay
*/
public static final SocketOption<Boolean> TCP_NODELAY =
new StdSocketOption<Boolean>("TCP_NODELAY", Boolean.class);
private static class StdSocketOption<T> implements SocketOption<T> {
private final String name;
private final Class<T> type;
StdSocketOption(String name, Class<T> type) {
this.name = name;
this.type = type;
}
@Override public String name() { return name; }
@Override public Class<T> type() { return type; }
@Override public String toString() { return name; }
}
}