Java nio 连接正在创建多个套接字级别的连接,为什么? [英] Java nio connection is creating multiple socket level connections, Why?
问题描述
我写了一个简单的java nio程序,如下所示
I have written a simple java nio program like the below
public static void main(String[] args) throws IOException, InterruptedException {
InetSocketAddress address = new InetSocketAddress("127.0.0.1",1001);
Selector incomingMessageSelector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
//到这里代码创建了到端口 52209 和 52210 的前 2 个连接
// Till here the code creates the top 2 connections to port 52209 and 52210
socketChannel.connect(address);
socketChannel.register(incomingMessageSelector, SelectionKey.OP_CONNECT);
socketChannel.register(incomingMessageSelector, SelectionKey.OP_WRITE);
socketChannel.register(incomingMessageSelector, SelectionKey.OP_READ);
//然后它会创建 2 个到端口 1001 的连接
// Then it creates 2 connections to port 1001
Thread.sleep(900000L);
}
我想了解为什么它会创建 4 个连接,而使用标准 TCP 阻塞库,它往往会创建 2 个连接.
I want to understand why it creates 4 connections, with the standard TCP blocking library it tends to create 2 connections.
我使用 JDK 1.7 和 Windows 7.
I use JDK 1.7 and Windows 7.
在图像中,只有 4 个突出显示的连接是由客户端创建的.
In the image only the 4 highlighted connections are of interest which are created by the client.
用红色标记的连接 1 条目是服务器端口.
One connection 1 entry marked with red is the server port.
PFA 显示这 4 个连接的图像.
PFA a image which shows these 4 connections.!
嗯,我真的最不明白为什么
Well i acutally most puzzled about why
Selector incomingMessageSelector = Selector.open();
在动态端口上创建连接
推荐答案
1001 和 52211 之间的连接显示两次,每个方向一次,因为两个端口都是本地端口.
The connection between 1001 and 52211 is being shown twice, once in each direction, as both ports are local.
一个选择器可能会打开另一个侦听套接字,以防它必须处理子选择器,以免超过每个选择器的最大套接字数.
A Selector may open another listening socket in case it has to handle sub-selectors so as not to exceed the maximum number of sockets per selector.
在完成 OP_CONNECT pgphasr 之前,您不应注册 OP_READ 或 OP_WRITE,此时您还应该注销 OP_CONNECT.同时注册这三个人绝对是错误的.
You shouldn't register OP_READ or OP_WRITE until after you've finished the OP_CONNECT pgphasr, when you should also deregister OP_CONNECT. Having all three of those registered at the same time is definitely wrong.
这篇关于Java nio 连接正在创建多个套接字级别的连接,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!