- Socket配置参数的含义
- Windows Socket 最大连接数
- connect timeout和so timeout的应用
- MySQL jdbc timeout">1 . MySQL jdbc timeout
- 2. Jedis timeout
- NIO源码
Socket配置参数的含义
Socket SoLinger
在Java Socket中,当我们调用Socket的close方法时,默认的行为是当底层网卡所有数据都发送完毕后,关闭连接
通过setSoLinger方法,我们可以修改close方法的行为
- setSoLinger(true, 0)
- 当网卡收到关闭连接请求后,无论数据是否发送完毕,立即发送RST包关闭连接
- setSoLinger(true, delay_time)
当网卡收到关闭连接请求后,等待delay_time
如果在delay_time过程中数据发送完毕,正常四次挥手关闭连接
如果在delay_time过程中数据没有发送完毕,发送RST包关闭连接
Socket 的写超时
- connect(SocketAddress endpoint, int timeout) 连接超时
- setSoTimeout(int timeout) 写时超时
- socket的写超时
socket的写超时是基于TCP的超时重传。超时重传是TCP保证数据可靠性传输的一个重要机制,其原理是在发送一个数据报文后就开启一个计时器,在一定时间内如果没有得到发送报文的确认ACK,那么就重新发送报文。如果重新发送多次之后,仍没有确认报文,就发送一个复位报文RST,然后关闭TCP连接。首次数据报文发送与复位报文传输之间的时间差大约为9分钟,也就是说如果9分钟内没有得到确认报文,就关闭连接。但是这个值是根据不同的TCP协议栈实现而不同。
如果发送端调用write持续地写出数据,直到SendQ队列被填满。如果在SendQ队列已满时调用write方法,则write将被阻塞,直到SendQ有新的空闲空间为止,也就是说直到一些字节传输到了接收者套接字的RecvQ中。如果此时RecvQ队列也已经被填满,所有操作都将停止,直到接收端调用read方法将一些字节传输到应用程序。
当Socket的write发送数据时,如果网线断开、对端进程崩溃或者对端机器重启动,TCP模块会重传数据,最后超时而关闭连接。下次如再调用write会导致一个异常而退出。
Socket写超时是基于TCP协议栈的超时重传机制,一般不需要设置write的超时时间,也没有提供这种方法。
Socket SoTimeout
/*** Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}* with the specified timeout, in milliseconds. With this option set* to a non-zero timeout, a read() call on the InputStream associated with* this Socket will block for only this amount of time. If the timeout* expires, a <B>java.net.SocketTimeoutException</B> is raised, though the* Socket is still valid. The option <B>must</B> be enabled* prior to entering the blocking operation to have effect. The* timeout must be {@code > 0}.* A timeout of zero is interpreted as an infinite timeout.** @param timeout the specified timeout, in milliseconds.* @exception SocketException if there is an error* in the underlying protocol, such as a TCP error.* @since JDK 1.1* @see #getSoTimeout()*/public synchronized int getSoTimeout() throws SocketException {if (isClosed())throw new SocketException("Socket is closed");Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);/* extra type safety */if (o instanceof Integer) {return ((Integer) o).intValue();} else {return 0;}}public synchronized void setSoTimeout(int timeout) throws SocketException {if (isClosed())throw new SocketException("Socket is closed");if (timeout < 0)throw new IllegalArgumentException("timeout can't be negative");getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));}
public void setSoTimeout(int timeout) throws SocketException使用指定的超时时间启用/禁用SO_TIMEOUT(以毫秒为单位)。 使用此选项设置为非零超时时,与此Socket相关联的InputStream上的read()调用将仅阻止此时间。如果超时超时,则引发java.net.SocketTimeoutException ,尽管Socket仍然有效。必须先启用该选项才能进入阻止操作才能生效。 超时时间必须为> 0 。 超时为零被解释为无限超时。参数: timeout - 指定的超时时间,以毫秒为单位。异常: SocketException - 如果底层协议有错误,如TCP错误。
/** Set a timeout on blocking Socket operations:* <PRE>* ServerSocket.accept();* SocketInputStream.read();* DatagramSocket.receive();* </PRE>** <P> The option must be set prior to entering a blocking* operation to take effect. If the timeout expires and the* operation would continue to block,* <B>java.io.InterruptedIOException</B> is raised. The Socket is* not closed in this case.** <P> Valid for all sockets: SocketImpl, DatagramSocketImpl** @see Socket#setSoTimeout* @see ServerSocket#setSoTimeout* @see DatagramSocket#setSoTimeout*/@Native public final static int SO_TIMEOUT = 0x1006;
@Nativestatic final int SO_TIMEOUT在阻塞套接字操作时设置超时:ServerSocket.accept();SocketInputStream.read();DatagramSocket.receive();必须先设置该选项才能进入阻止操作才能生效。 如果超时过期,并且操作将继续阻止,则引发java.io.InterruptedIOException 。 在这种情况下,Socket不关闭。适用于所有套接字:SocketImpl,DatagramSocketImpl另请参见:Socket.setSoTimeout(int) , ServerSocket.setSoTimeout(int) ,DatagramSocket.setSoTimeout(int) , Constant Field Values
如果输入缓冲队列RecvQ中没有数据,read操作会一直阻塞而挂起线程,直到有新的数据到来或者有异常产生。调用setSoTimeout(int timeout)可以设置超时时间,如果到了超时时间仍没有数据,read会抛出一个SocketTimeoutException,程序需要捕获这个异常,但是当前的socket连接仍然是有效的。
如果对方进程崩溃、对方机器突然重启、网络断开,本端的read会一直阻塞下去,这时设置超时时间是非常重要的,否则调用read的线程会一直挂起。
TCP模块把接收到的数据放入RecvQ中,直到应用层调用输入流的read方法来读取。如果RecvQ队列被填满了,这时TCP会根据滑动窗口机制通知对方不要继续发送数据,本端停止接收从对端发送来的数据,直到接收者应用程序调用输入流的read方法后腾出了空间。
代码说明SoTimeout
import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class ServerMain {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(8888);long t1 = 0;try {Socket socket = serverSocket.accept();System.out.println("服务端接收到一个连接");t1 = System.currentTimeMillis();//设置该通道的read()方法超时socket.setSoTimeout(5000);InputStream inputStream = accept.getInputStream();//read阻塞inputStream.read();} finally {System.out.println("服务端setSoTimeout 耗时:"+ (System.currentTimeMillis() - t1));}}}
import java.io.InputStream;import java.net.InetSocketAddress;import java.net.Socket;public class ClientMain {public static void main(String[] args) throws Exception {Socket socket = new Socket();socket.connect(new InetSocketAddress(8888));//设置超时时间socket.setSoTimeout(10000);InputStream inputStream = socket.getInputStream();long t1 = System.currentTimeMillis();try {inputStream.read();} finally {System.out.println("客户端setSoTimeout 耗时:"+ (System.currentTimeMillis() - t1));}}}
启动以后
服务端日志
服务端接收到一个连接服务端setSoTimeout 耗时:5007Exception in thread "main" java.net.SocketTimeoutException: Read timed outat java.net.SocketInputStream.socketRead0(Native Method)at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)at java.net.SocketInputStream.read(SocketInputStream.java:171)at java.net.SocketInputStream.read(SocketInputStream.java:141)at java.net.SocketInputStream.read(SocketInputStream.java:224)at cn.java.money.bio.demo9.ServerMain.main(ServerMain.java:21)
客户端日志
客户端setSoTimeout 耗时:5496Exception in thread "main" java.net.SocketException: Connection resetat java.net.SocketInputStream.read(SocketInputStream.java:210)at java.net.SocketInputStream.read(SocketInputStream.java:141)at java.net.SocketInputStream.read(SocketInputStream.java:224)at cn.java.money.bio.demo9.ClientMain.main(ClientMain.java:17)
说明:
soTimeout默认值是0,也就是没有超时时间,会无限的等待。
服务端抛出异常 java.net.SocketTimeoutException: Read timed out 是因为我们设置了soTimeout socket.setSoTimeout(5000); 但是客户端一致没有写数据,服务端读数据等待5000毫秒,超时就抛出异常SocketTimeoutException,抛出异常以后,该连接就会被关闭,向客户端发送了RST包。因此客户端收到的是java.net.SocketException: Connection reset (RST包)。https://www.yuque.com/protocal/tcp/nq74g5
Socket ReceiveBufferSize SendBufferSize
public synchronized int getReceiveBufferSize() throws SocketException{if (isClosed())throw new SocketException("Socket is closed");int result = 0;Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);if (o instanceof Integer) {result = ((Integer)o).intValue();}return result;}public synchronized void setReceiveBufferSize(int size)throws SocketException{if (size <= 0) {throw new IllegalArgumentException("invalid receive size");}if (isClosed())throw new SocketException("Socket is closed");getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));}public synchronized int getSendBufferSize() throws SocketException {if (isClosed())throw new SocketException("Socket is closed");int result = 0;Object o = getImpl().getOption(SocketOptions.SO_SNDBUF);if (o instanceof Integer) {result = ((Integer)o).intValue();}return result;}public synchronized void setSendBufferSize(int size)throws SocketException{if (!(size > 0)) {throw new IllegalArgumentException("negative send size");}if (isClosed())throw new SocketException("Socket is closed");getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));}//java.net.SocketOptions@Native public final static int SO_RCVBUF = 0x1002;@Native public final static int SO_SNDBUF = 0x1001;
ServerSocket backlog
public ServerSocket(int port, int backlog) throws IOException {this(port, backlog, null);}
backlog 最终作用于Linux的参数 tcp_max_syn_backlog
[root@JD1 ~]# cat /proc/sys/net/ipv4/tcp_max_syn_backlog256[root@JD1 ~]# sysctl -a|grep tcp_max_syn_backlognet.ipv4.tcp_max_syn_backlog = 256
tcp_max_syn_backlog 影响的是 半连接队列和全连接队列的大小


(somaxconn 推测是 socket max connection 缩写)
[root@JD1 ~]# sysctl -a|grep net.core.somaxconnnet.core.somaxconn = 128[root@JD1 ~]# cat /proc/sys/net/core/somaxconn128


代码测试backlog
import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class ServerMain {public static void main(String[] args) throws IOException {//设置backlog为2, 最多只能有3个客户端(2个在全连接队列中+1个accept的)ServerSocket serverSocket = new ServerSocket(8888, 2);Socket accept = serverSocket.accept();InputStream inputStream = accept.getInputStream();inputStream.read();}}
public class ClientMain {public static void main(String[] args) throws Exception {Socket socket = new Socket();socket.connect(new InetSocketAddress("127.0.0.1", 8888));InputStream inputStream = socket.getInputStream();inputStream.read();}}
Socket connectTimeOut
1. Socket connectTimeOut 在JDK中
public Socket(InetAddress address, int port) throws IOException {this(address != null ? new InetSocketAddress(address, port) : null,(SocketAddress) null, true);}private Socket(SocketAddress address, SocketAddress localAddr,boolean stream) throws IOException {setImpl();// backward compatibilityif (address == null)throw new NullPointerException();try {createImpl(stream);if (localAddr != null)bind(localAddr);connect(address);} catch (IOException | IllegalArgumentException | SecurityException e) {try {close();} catch (IOException ce) {e.addSuppressed(ce);}throw e;}}public void connect(SocketAddress endpoint) throws IOException {//默认超时时间为0connect(endpoint, 0);}/*** Connects this socket to the server with a specified timeout value.* A timeout of zero is interpreted as an infinite timeout. The connection* will then block until established or an error occurs.** @param endpoint the {@code SocketAddress}* @param timeout the timeout value to be used in milliseconds.* @throws IOException if an error occurs during the connection* @throws SocketTimeoutException if timeout expires before connecting* @throws java.nio.channels.IllegalBlockingModeException* if this socket has an associated channel,* and the channel is in non-blocking mode* @throws IllegalArgumentException if endpoint is null or is a* SocketAddress subclass not supported by this socket* @since 1.4* @spec JSR-51*/public void connect(SocketAddress endpoint, int timeout) throws IOException {//省略}//java.net.DualStackPlainSocketImpl#connect0static native int connect0(int fd, InetAddress remote, int remotePort) throws IOException;

默认超时时间为0,意味着没有设置超时时间,连接是不是过期的。
2. Socket 连接建立超时表现在TCP协议
socket连接建立是基于TCP的连接建立过程。TCP的连接需要通过3次握手报文来完成,开始建立TCP连接时需要发送同步SYN报文,然后等待确认报文SYN+ACK,最后再发送确认报文ACK。TCP连接的关闭通过4次挥手来完成,主动关闭TCP连接的一方发送FIN报文,等待对方的确认报文;被动关闭的一方也发送FIN报文,然等待确认报文。
正在等待TCP连接请求的一端有一个固定长度的连接队列,该队列中的连接已经被TCP接受(即三次握手已经完成),但还没有被应用层所接受。TCP接受一个连接是将其放入这个连接队列,而应用层接受连接是将其从该队列中移出。应用层可以通过设置backlog变量来指明该连接队列的最大长度,即已被TCP接受而等待应用层接受的最大连接数。
当一个连接请求SYN到达时,TCP确定是否接受这个连接。如果队列中还有空间,TCP模块将对SYN进行确认并完成连接的建立。但应用层只有在三次握手中的第三个报文收到后才会知道这个新连接。如果队列没有空间,TCP将不理会收到的SYN。
如果应用层不能及时接受已被TCP接受的连接,这些连接可能占满整个连接队列,新的连接请求可能不被响应而会超时。如果一个连接请求SYN发送后,一段时间后没有收到确认SYN+ACK,TCP会重传这个连接请求SYN两次,每次重传的时间间隔加倍,在规定的时间内仍没有收到SYN+ACK,TCP将放弃这个连接请求,连接建立就超时了。
JAVA Socket连接建立超时和TCP是相同的,如果TCP建立连接时三次握手超时,那么导致Socket连接建立也就超时了。可以设置Socket连接建立的超时时间 connect(SocketAddress endpoint, int timeout)
如果在timeout内,连接没有建立成功,在TimeoutException异常被抛出。如果timeout的值小于三次握手的时间,那么Socket连接永远也不会建立。
不同的应用层有不同的连接建立过程,Socket的连接建立和TCP一样-仅仅需要三次握手就完成连接,但有些应用程序需要交互很多信息后才能成功建立连接,比如Telnet协议,在TCP三次握手完成后,需要进行选项协商之后,Telnet连接才建立完成。
3. 代码测试
import java.net.InetSocketAddress;import java.net.Socket;public class ClientMain {public static void main(String[] args) throws Exception {Socket socket = new Socket();long t1 = System.currentTimeMillis();// 设置 connection timeout (单位毫秒)try {//ip地址是随意写的//socket.connect(new InetSocketAddress("192.168.2.145",8888));//设置超时时间socket.connect(new InetSocketAddress("192.168.2.145",8888), 5000);} finally {System.out.println("客户端connection Timeout 耗时:"+ (System.currentTimeMillis() - t1) + "毫秒");}}}
设置了 timout
客户端connection Timeout 耗时:5011毫秒 Exception in thread “main” java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394) at java.net.Socket.connect(Socket.java:606) at ClientMain.main(ClientMain.java:11)
未设置timout, 为什么是20秒左右,不知道原因。将来慢慢研究一下。
客户端connection Timeout 耗时:21010毫秒 Exception in thread “main” java.net.ConnectException: 拒绝连接 (Connection refused) at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394) at java.net.Socket.connect(Socket.java:606) at java.net.Socket.connect(Socket.java:555) at ClientMain.main(ClientMain.java:10)
Socket keepalive
- Socket keepalive的配置本质是TCP的保活机制。
- Socket是客户端和服务端建立的虚拟通信通道。客户端的Socket和服务端的Socket逻辑上是同一个。
- Java Socket编程中有个keepalive选项不是用来表示长链接的。
socket 连接建立之后,只要双方均未主动关闭连接,那这个连接就是会一直保持的,就是持久的连接
keepalive 只是为了防止连接的双方发生意外而通知不到对方,导致一方还持有连接,占用资源。java.net.Socket#setKeepAlive ```java public void setKeepAlive(boolean on) throws SocketException { if (isClosed())
throw new SocketException("Socket is closed");
getImpl().setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(on)); }
public boolean getKeepAlive() throws SocketException { if (isClosed()) throw new SocketException(“Socket is closed”); return ((Boolean) getImpl().getOption(SocketOptions.SO_KEEPALIVE)).booleanValue(); }
```javapublic interface SocketOptions {/*** When the keepalive option is set for a TCP socket and no data* has been exchanged across the socket in either direction for* 2 hours (NOTE: the actual value is implementation dependent),* TCP automatically sends a keepalive probe to the peer. This probe is a* TCP segment to which the peer must respond.* One of three responses is expected:* 1. The peer responds with the expected ACK. The application is not* notified (since everything is OK). TCP will send another probe* following another 2 hours of inactivity.* 2. The peer responds with an RST, which tells the local TCP that* the peer host has crashed and rebooted. The socket is closed.* 3. There is no response from the peer. The socket is closed.** The purpose of this option is to detect if the peer host crashes.** Valid only for TCP socket: SocketImpl** @see Socket#setKeepAlive* @see Socket#getKeepAlive*/@Native public final static int SO_KEEPALIVE = 0x0008; //0x0008表示的是操作id}
源码注释的意思是,如果这个连接上双方任意方向在2小时之内没有发送过数据,那么tcp会自动发送一个探测探测包给对方,这种探测包对方是必须回应的,回应结果有三种:
- 正常ACK,继续保持连接;
- 对方响应RST信号,双方重新连接。
- 对方无响应。
这里说的两小时,其实是依赖于系统配置,在linux系统中(windows在注册表中,可以自行查询资料),tcp的keepalive参数。
[root@JD1 ~]# sysctl -a|grep tcp_keepalivenet.ipv4.tcp_keepalive_intvl = 75net.ipv4.tcp_keepalive_probes = 9net.ipv4.tcp_keepalive_time = 7200
- net.ipv4.tcp_keepalive_intvl = 75
- 发送探测包的周期,前提是当前连接一直没有数据交互,才会以该频率进行发送探测包,如果中途有数据交互,则会重新计时tcp_keepalive_time,到达规定时间没有数据交互,才会重新以该频率发送探测包
- net.ipv4.tcp_keepalive_probes = 9
- 探测失败的重试次数,发送探测包达次数限制对方依旧没有回应,则关闭自己这端的连接
- net.ipv4.tcp_keepalive_time = 7200
- 空闲多长时间,则发送探测包
可以通过 sysctl -w net.ipv4.tcp_keepalive_time=60进行修改,执行sysctl -p刷新配置生效;
可以通过修改/etc/sysctl.conf永久生效
当建立TCP链接后,如果应用程序或者上层协议一直不发送数据,或者隔很长一段时间才发送数据,当链接很久没有数据报文传输时就需要通过keepalive机制去确定对方是否在线,链接是否需要继续保持。当超过一定时间没有发送数据时,TCP会自动发送一个数据为空的报文给对方,如果对方回应了报文,说明对方在线,链接可以继续保持,如果对方没有报文返回,则在重试一定次数之后认为链接丢失,就不会释放链接。
控制对闲置连接的检测机制,链接闲置达到7200秒,就开始发送探测报文进行探测。
net.ipv4.tcp_keepalive_time:单位秒,表示发送探测报文之前的链接空闲时间,默认为7200。
net.ipv4.tcp_keepalive_intvl:单位秒,表示两次探测报文发送的时间间隔,默认为75。
net.ipv4.tcp_keepalive_probes:表示探测的次数,默认9次。
为了能验证所说的,我们来进行测试一下,本人测试环境是客户端在本地windows上,服务端是在远程linux上,主要测试服务器端向客户端发送探测包(客户端向服务端发送是一样的原理,这里测试服务器端到客户端的原因是我们修改了服务端的keep-alive便于观察)。
- 首先需要装一个抓包工具,本人用的wireshark;
- 然后修改一下tcp_keepalive_time系统配置,改成1分钟,2小时太长了,其余配置不变。
修改方法:执行sysctl -w net.ipv4.tcp_keepalive_time=60进行修改,执行sysctl -p刷新配置生效;
- 最后写一个服务器端和一个客户端,分别启动。
服务器端代码如下(java8):
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class Server {public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(12345);while (true) {//建立虚拟连接通道Socket socket = ss.accept();new Thread(() -> {try {//开启keppAlive机制socket.setKeepAlive(true);socket.setReceiveBufferSize(8 * 1024);socket.setSendBufferSize(8 * 1024);InputStream is = socket.getInputStream();OutputStream os = socket.getOutputStream();try {byte[] bytes = new byte[1024];while (is.read(bytes) > -1) {System.out.println(System.currentTimeMillis()+ " received message: "+ new String(bytes, "UTF-8").trim());os.write("ok".getBytes("UTF-8"));os.flush();bytes = new byte[1024];}} catch (IOException e) {e.printStackTrace();} finally {if (!socket.isInputShutdown()) {socket.shutdownInput();}if (!socket.isOutputShutdown()) {socket.shutdownOutput();}if (!socket.isClosed()) {socket.close();}}} catch (IOException e) {e.printStackTrace();}}).start();}}}
客户端代码如下:
public class Client {public static void main(String[] args) throws IOException, InterruptedException {Socket socket = new Socket("192.168.16.84", 12345);//开启tcp的keepAlive机制socket.setKeepAlive(true);socket.setSendBufferSize(8192);socket.setReceiveBufferSize(8192);InputStream is = socket.getInputStream();OutputStream os = socket.getOutputStream();os.write("get test-key".getBytes("UTF-8"));os.flush();Thread.sleep(155 * 1000L);os.write("get test-key".getBytes("UTF-8"));os.flush();byte[] bytes = new byte[1024];while (is.read(bytes) > -1) {System.out.println(System.currentTimeMillis()+ " received message: "+ new String(bytes, "UTF-8").trim());bytes = new byte[1024];}if (!socket.isOutputShutdown()) {socket.shutdownOutput();}if (!socket.isInputShutdown()) {socket.shutdownInput();}if (!socket.isClosed()) {socket.close();}}}
分别启动服务端和客户端之后,抓包工具抓到的数据:
可以看到,60秒时服务器发送了探测包,探测客户端是否正常,客户端正常响应了,之后以tcp_keepalive_intvl(75秒)的周期进行发送,可以看到135秒又进行发送了探测包。
但是因为我们客户端的代码是在155秒重新发送了数据,所以需要继续空闲60秒,直到215秒才继续发送探测包,后续没有数据交互,所以还是以75秒间隔频率进行发送探测包。从抓包的数据上很容易看出来。
keepalive默认是关闭的,下面我们把服务器端的socket.setKeepAlive(true)一行注释掉的抓包结果:
可以看到服务器端没有向客户端发送探测包,其实客户端设置了socket.setKeepAlive(true),客户端在7355(7200+155)秒时应该会向服务器发送探测包(我把程序挂了2小时。。。结果如下)
验证无误。
windows下的tcp keepalive
缺省情况下,如果空闲连接在7200000毫秒(2小时)内没有活动,系统就会发送保持连接的消息。 具体操作:浏览至HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TCPIP\Parameters 注册表子键,在Parameters子键下创建或修改名为KeepAliveTime的REG_DWORD值,为该值设置适当的毫秒数。
socket 连接建立之后,只要双方均未主动关闭连接,那这个连接就是会一直保持的,就是持久的连接
keepalive 只是为了防止连接的双方发生意外而通知不到对方,导致一方还持有连接,占用资源。
其实这个选项的意思是TCP连接空闲时是否需要向对方发送探测包,实际上是依赖于底层的TCP模块实现的,java中只能设置是否开启,不能设置其详细参数,只能依赖于系统配置。
keepalive 不是说TCP的长连接,当我们作为服务端,一个客户端连接上来,如果设置了keeplive为 true,当对方没有发送任何数据过来,超过一个时间(看系统内核参数配置),那么我们这边会发送一个ack探测包发到对方,探测双方的TCP/IP连接是否有效(对方可能断电,断网)。如果不设置,那么客户端宕机时,服务器永远也不知道客户端宕机了,仍然保存这个失效的连接。
当然,在客户端也可以使用这个参数。客户端Socket会每隔段的时间(大约两个小时)就会利用空闲的连接向服务器发送一个数据包。这个数据包并没有其它的作用,只是为了检测一下服务器是否仍处于活动状态。如果服务器未响应这个数据包,在大约11分钟后,客户端Socket再发送一个数据包,如果在12分钟内,服务器还没响应,那么客户端Socket将关闭。如果将Socket选项关闭,客户端Socket在服务器无效的情况下可能会长时间不会关闭。
Windows Socket 最大连接数
TCP/IP 协议规定的,只用了2个字节表示端口号。容易让人误解为1个server只允许连接65535个Client。
typedef struct _NETWORK_ADDRESS_IP
{
USHORT sin_port;//0~65535
ULONG in_addr;
UCHAR sin_zero[8];
} NETWORK_ADDRESS_IP, *PNETWORK_ADDRESS_IP;
(1)其实65535这个数字,只是决定了服务器端最多可以拥有65535个Bind的Socket。也就是说,最多可以开65535个服务器进程,但是你要知道这个能够连接客户端的数量没有任何关系,Accept过来的Socket是不需要Bind任何IP地址的,也没有端口占用这一说。作为Server端的Socket本身只负责监听和接受连接操作。
(2)TCP协议里面是用[源IP+源Port+目的IP+目的 Port]来区别两个不同连接,所以连入和连出是两个不同的概念。连出Connect就不错了,需要生成随机端口,这个是有限的连入的话, 因SOCKET的分配受内存分页限制,而连接受限制(WINDOWS)。
(3)所以,千万不要误以为1个server只允许连接65535个Client。记住,TCP连出受端口限制,连入仅受内存限制。
例如server,IP:192.168.16.254,Port:8009
Client1:IP:192.168.16.1,Port:2378
Client2:IP:192.168.16.2,Port:2378
Client1和Client2虽然Port相同,但是IP不同,所以是不同的连接。
(4)想让1个server并发高效得连接几万个Client,需要使用IOCP“完成端口(Completion Port)”的技术。
详情请参考文章:http://blog.csdn.net/libaineu2004/article/details/40087167
connect timeout和so timeout的应用
1 . MySQL jdbc timeout
查阅MySQL Connector/J 5.1 Developer Guide 中的jdbc配置参数,有
| connectTimeout Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to ‘0’. Default: 0 Since version: 3.0.1 |
|---|
| socketTimeout Timeout on network socket operations (0, the default means no timeout). Default: 0 Since version: 3.0.1 |
这两个参数分别就是对应上面我们分析的connect timeout和so timeout。
参数的设置方法有两种,一种是通过url设置,
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]][?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
即在url后面通过?加参数,比如jdbc:mysql://192.168.1.1:3306/test?connectTimeout=2000&socketTime=2000
还有一种方式是:
Properties info = new Properties();info.put("user", this.username);info.put("password", this.password);info.put("connectTimeout", "2000");info.put("socketTime", "2000");return DriverManager.getConnection(this.url, info);
2. Jedis timeout
Jedis是最流行的redis java客户端工具,redis.clients.jedis.Jedis对象的构造器中就有参数设置,
public Jedis(final String host, final int port, final int connectionTimeout,final int soTimeout) {super(host, port, connectionTimeout, soTimeout);}
// 用一个参数timeout同时设置connect timeout 和 so timeoutpublic Jedis(final String host, final int port, final int timeout) {super(host, port, timeout);}
Jedis中so timeout个人觉得是有比较重要意义的,首先jedis so timeout默认值为2000毫秒,jedis的操作流程是客户端发送命令给客户端执行,然后客户端就开始执行InputStream.read()读取响应,当某个命令比较耗时(比如数据非常多的情况下执行“keys *”),而导致客户端迟迟没有收到响应,就可能导致java.net.SocketTimeoutException: Read timed out异常抛出。一般是不建议客户端执行非常耗时的命令,但是也不排除有这种特殊逻辑,那这时候就有可能需要修改Jeids中这个so timeout的值。
NIO源码
1. NIO 模型代码

NIO 的 selector解决了很多连接不需要遍历每一个Channel的问题。
selector.select() 阻塞等待需要处理的事件发生。
package cn.java.money.nio.demo2;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;public class Server {public static void main(String[] args) throws IOException {//首先的有一个通道,接受连接ServerSocketChannel ssChannel = ServerSocketChannel.open();ssChannel.configureBlocking(false);ssChannel.bind(new InetSocketAddress(8888));Selector selector = Selector.open();ssChannel.register(selector, SelectionKey.OP_ACCEPT);//select会在这里阻塞while (selector.select() > 0) {//通过Selector,只遍历有事件的channel去处理Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();while (iterator.hasNext()) {SelectionKey selectionKey = iterator.next();if (selectionKey.isAcceptable()) {SocketChannel socketChannel = ssChannel.accept();socketChannel.configureBlocking(false);socketChannel.register(selector, SelectionKey.OP_READ);} else if (selectionKey.isReadable()) {SocketChannel channel = (SocketChannel) selectionKey.channel();ByteBuffer byteBuffer = ByteBuffer.allocate(1024);int length = 0;//channel.read(byteBuffer)是把数据读入byteBuffer,此时byteBuffer的模式是写入模式// 如果某个通道的数据量很多,这里就会长时间处理,就会影响其他channelwhile ((length = channel.read(byteBuffer)) > 0) {byteBuffer.flip();//相当于读取数据,从buffer中读取数据System.out.println(new String(byteBuffer.array(), 0, length));byteBuffer.clear();}}//事件处理完要移除iterator.remove();}}}}
package cn.java.money.nio.demo2;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;import java.util.Scanner;public class Client {public static void main(String[] args) throws IOException {SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));socketChannel.configureBlocking(false);ByteBuffer byteBuffer = ByteBuffer.allocate(1024);Scanner scanner = new Scanner(System.in);while (true){String s = scanner.nextLine();//buffer写模式byteBuffer.put(s.getBytes());//切换为读模式byteBuffer.flip();//写到channel,就是从buffer中读取socketChannel.write(byteBuffer);byteBuffer.clear();}}}
2. NIO 源码 Linux版本代码
https://gitee.com/framework-src/openjdk-1.8-b132.git
2.1 Selector.open()
Selector selector = Selector.open();public static Selector open() throws IOException {return SelectorProvider.provider().openSelector();}public static SelectorProvider provider() {return sun.nio.ch.DefaultSelectorProvider.create();}不同操作系统的JDK提供了不同的 DefaultSelectorProvider,不同的DefaultSelectorProvider返回不同的SelectorProvider的实现--- Windown 版本JDKWindowsSelectorProviderWindowsSelectorImpl--- Linux 版本JDKEPollSelectorProviderEPollSelectorImpl
不同操作系统的JDK提供了不同的 DefaultSelectorProvider

solaris的 DefaultSelectorProvider
public static SelectorProvider create() {String osname = AccessController.doPrivileged(new GetPropertyAction("os.name"));if (osname.equals("SunOS"))return createProvider("sun.nio.ch.DevPollSelectorProvider");if (osname.equals("Linux"))return createProvider("sun.nio.ch.EPollSelectorProvider");return new sun.nio.ch.PollSelectorProvider();}
sun.nio.ch.EPollSelectorProvider
public class EPollSelectorProvider extends SelectorProviderImpl{public AbstractSelector openSelector() throws IOException {return new EPollSelectorImpl(this);}public Channel inheritedChannel() throws IOException {return InheritedChannel.getChannel();}}
EPollSelectorImpl(SelectorProvider sp) throws IOException {super(sp);long pipeFds = IOUtil.makePipe(false);fd0 = (int) (pipeFds >>> 32);fd1 = (int) pipeFds;pollWrapper = new EPollArrayWrapper();pollWrapper.initInterrupt(fd0, fd1);fdToKey = new HashMap<>();}
EPollArrayWrapper() throws IOException {// creates the epoll file descriptorepfd = epollCreate();// the epoll_event array passed to epoll_waitint allocationSize = NUM_EPOLLEVENTS * SIZE_EPOLLEVENT;pollArray = new AllocatedNativeObject(allocationSize, true);pollArrayAddress = pollArray.address();// eventHigh needed when using file descriptors > 64kif (OPEN_MAX > MAX_UPDATE_ARRAY_SIZE)eventsHigh = new HashMap<>();}//native方法 是 epoll最核心的几个方法由linux操作系统实现private native int epollCreate(); //返回epoll文件描述符//epfd是epoll的文件描述符,对应Selector//fd是ServerSocketChannel的文件描述符private native void epollCtl(int epfd, int opcode, int fd, int events);private native int epollWait(long pollAddress, int numfds, long timeout, int epfd)throws IOException;
epoll_create(256) 返回文件描述符
epoll_create 打开一个epoll文件的描述符。c 语言创建的epoll的实例,就是结构体,用于存储数据。
epfd 是返回的文件描述符。
2.2 ssChannel.register(selector, SelectionKey.OP_ACCEPT);
sun.nio.ch.WindowsSelectorImpl#implRegister
sun.nio.ch.EPollSelectorImpl#implRegister
protected void implRegister(SelectionKeyImpl ski) {if (closed)throw new ClosedSelectorException();SelChImpl ch = ski.channel;int fd = Integer.valueOf(ch.getFDVal());fdToKey.put(fd, ski);// fd 就是ServerSocketChannel的文件描述符pollWrapper.add(fd);keys.add(ski);}
2.3 selector.select()
sun.nio.ch.WindowsSelectorImpl#doSelect
sun.nio.ch.EPollSelectorImpl#doSelect
protected int doSelect(long timeout) throws IOException {if (closed)throw new ClosedSelectorException();processDeregisterQueue();try {begin();// 轮询pollWrapper.poll(timeout);} finally {end();}processDeregisterQueue();int numKeysUpdated = updateSelectedKeys();if (pollWrapper.interrupted()) {// Clear the wakeup pipepollWrapper.putEventOps(pollWrapper.interruptedIndex(), 0);synchronized (interruptLock) {pollWrapper.clearInterrupted();IOUtil.drain(fd0);interruptTriggered = false;}}return numKeysUpdated;}
sun.nio.ch.EPollArrayWrapper#poll
int poll(long timeout) throws IOException {//epollCtlupdateRegistrations();//epollWai 是一个nativea方法updated = epollWait(pollArrayAddress, NUM_EPOLLEVENTS, timeout, epfd);for (int i=0; i<updated; i++) {if (getDescriptor(i) == incomingInterruptFD) {interruptedIndex = i;interrupted = true;break;}}return updated;}private void updateRegistrations() {epollCtl(epfd, opcode, fd, events);}private native void epollCtl(int epfd, int opcode, int fd, int events);private native int epollWait(long pollAddress, int numfds, long timeout, int epfd)throws IOException;
3. select poll epoll的区别

