gpt4 book ai didi

java - 使用 NIO SocketChannel 连接到套接字超时

转载 作者:行者123 更新时间:2023-11-29 03:34:18 25 4
gpt4 key购买 nike

<分区>

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

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

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

这个类工作得很好,除非主机关闭,然后 SocketChannel.open 永远阻塞。我试图通过执行以下操作来使此超时:

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() 永远阻塞,而我本以为它根本不会阻塞。有什么想法吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com