NIO 关于SocketChannel的isConnected与finishConnect区别

-----重要的先说-----

区别:

1、isConnected是判断是否连接成功的,如果连接成功,则true,否则false;源码如下:

NIO 关于SocketChannel的isConnected与finishConnect区别_第1张图片

NIO 关于SocketChannel的isConnected与finishConnect区别_第2张图片

通过上面两张图能够知道,isConnected只有当状态为2(已连接时)才会返回true。

2、finishConnect是判断连接是否完成

(看起来和isConnected一样,但是,finishConnect内部会主动抛异常,isConnected则不会【线程中断异常那不算】)

请看源码,然后慢慢解释

NIO 关于SocketChannel的isConnected与finishConnect区别_第3张图片

如果已连接(状态为2),则true;否则,如果不处于已连接状态,并且不是正在连接(pending),就会抛异常,然后其他情况旧放那会false

 

下面是我看到令我得到以上结果的一篇博客的片段。。。令我恍然大悟的。

来自https://blog.csdn.net/billluffy/article/details/78036998

connect事件(连接--成功or失败?)

在之前的Socket通道中,已经看到,非阻塞模式下,connect操作会返回false,后面会发出CONNECT事件来表示连接,但是这里其实没有区分成功还是失败。。

 

connect事件:表示连接通道连接就绪或者发生了错误,会被加到ready 集合中(下面面是API说明)

If the selector detects that the corresponding socket channel is ready to complete its connection sequence, or has an error pending, then it will add OP_CONNECT to the key's ready set and add the key to its selected-key set.

 

所以这个事件发生的时候不能简单呢的认为连接成功,要使用finishConnect判断下,如果连接失败,会抛出异常

NIO就绪处理之OP_CONNECT
 

1if (key.isValid() && key.isConnectable()) { 

2    SocketChannel ch = (SocketChannel) key.channel(); 

3    if (ch.finishConnect()) { 

4        // Connect successfully 

5        // key.interestOps(SelectionKey.OP_READ); 

6    } else { 

7        // Connect failed 

8    } 

9}

你可能感兴趣的:(java,NIO)