Java NIO(三)非阻塞的连接操作
2021-03-18 00:25
标签:throws each conf catch blocking reg github trace 连接 代码如下: 我们修改下上面的代码,将 改成 注意要确保主机"192.168.2.1"是不可达的。 我们看到结果的第一行以及第四行,可以得到一个结论:不管连接成功还是失败,selector都会报isConnectable事件,然而至于成功还是失败,需要调用SocketChannel的finishConnect来判断。 Java NIO(三)非阻塞的连接操作 标签:throws each conf catch blocking reg github trace 连接 原文地址:https://www.cnblogs.com/ralgo/p/13963170.html异步连接需要做以下操作:
public class Client1 {
Selector selector;
int writeEventTrigerCount = 0;
public void run() throws IOException {
selector = Selector.open();
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_CONNECT);
sc.connect(new InetSocketAddress("182.61.200.6", 80));
while (true) {
selector.select();
Set
连接失败会发生什么?
sc.connect(new InetSocketAddress("182.61.200.6", 80));
sc.connect(new InetSocketAddress("192.168.2.1", 80));
运行代码,等待几秒钟,会出现下面内容:sun.nio.ch.SelectionKeyImpl@1d81eb93 connected
java.net.ConnectException: Connection timed out: no further information
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
at com.github.ralgond.nioexample.ClientConnectToUnreachableHost.run(ClientConnectToUnreachableHost.java:31)
at com.github.ralgond.nioexample.ClientConnectToUnreachableHost.main(ClientConnectToUnreachableHost.java:50)
上一篇:Java动态绑定
文章标题:Java NIO(三)非阻塞的连接操作
文章链接:http://soscw.com/index.php/essay/65537.html