使用NIO SocketChannel连接到套接字超时 [英] Timeout on connect to socket using NIO SocketChannel

查看:1504
本文介绍了使用NIO SocketChannel连接到套接字超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个类通过套接字与另一个HOST通信,它看起来像这样:

We have a class that is talking to another HOST over a socket and it looks like this:

SocketChannel sc = SocketChannel.open(new InetSocketAddress(HOST, PORT));
sc.configureBlocking(true);

...
sc.write(...)
sc.read(...)

除非HOST已关闭,否则SocketChannel.open将永久阻止,此类工作正常。我尝试通过执行以下操作来实现此超时:

This class works great except if the HOST is down then SocketChannel.open blocks forever. I've tried to make this timeout by doing the following:

SocketChannel  = SocketChannel.open();
sc.configureBlocking(false);
boolean result = socketChannel.connect(new InetSocketAddress(HOST, PORT));
if (!result) {
    long startTime = System.currentTimeMillis();
    while (!socketChannel.finishConnect()) {
        if (System.currentTimeMillis() - startTime< 1000) {
            // keep trying
            Thread.sleep(100);
        } else {
            // FAILED!
            enabled = false;
            return;
        }
    }
}
// SUCCESS!
socketChannel.configureBlocking(true);
enabled = true

由于某种原因,当我有的时候,finishConnect()会永远阻止预计它根本不会阻止。有什么想法?

Well for some reason finishConnect() is blocking forever when I would have expected it to not block at all. Any ideas?

推荐答案

你做错了。


  1. 创建一个未连接的 SocketChannel 并在阻止模式下进行定时连接。

  1. Create an unconnected SocketChannel and do a timed connect in blocking mode.

OR


  1. 使用选择器在非阻塞模式下。注册 OP_CONNECT 的频道并选择。当它变得可连接时,调用 finishConnect(),,如果它返回true,则取消注册 OP_CONNECT 并继续进行I / O操作。如果返回false,请继续选择。如果它抛出异常,放弃连接,它就失败了。使用选择超时。不是旋转循环。

  1. Use a Selector in non-blocking mode. Register the channel for OP_CONNECT and select. When it becomes connectable, call finishConnect(), and if it returns true deregister OP_CONNECT and proceed with the I/O. If it returns false, keep selecting. If it throws an exception, give up of the connection, it has failed. Use the select timeout. Not a spin loop.

这篇关于使用NIO SocketChannel连接到套接字超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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