Java nio连接正在创建多个套接字级连接,为什么? [英] Java nio connection is creating multiple socket level connections, Why?

查看:153
本文介绍了Java nio连接正在创建多个套接字级连接,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的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);
}

我想了解为什么它使用标准TCP阻塞库创建4个连接它倾向于创建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.!

我最为困惑的是为什么

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_READ或OP_WRITE完成OP_CONNECT pgphasr后,你还应该取消注册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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆