From e5ac20fd1ed479cd0e9372304bdfc5c1c3fa991d Mon Sep 17 00:00:00 2001 From: "Brian P. Hinz" Date: Sun, 19 Feb 2017 23:59:03 -0500 Subject: [PATCH] Downed hosts should timeout reasonably quickly --- java/com/tigervnc/network/TcpSocket.java | 43 +++++++++++++++++------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/java/com/tigervnc/network/TcpSocket.java b/java/com/tigervnc/network/TcpSocket.java index 43787e4d..95f16d3a 100644 --- a/java/com/tigervnc/network/TcpSocket.java +++ b/java/com/tigervnc/network/TcpSocket.java @@ -32,6 +32,9 @@ import java.net.UnknownHostException; import java.nio.*; import java.nio.channels.*; +import java.util.Set; +import java.util.Iterator; + public class TcpSocket extends Socket { // -=- Socket initialisation @@ -77,23 +80,37 @@ public class TcpSocket extends Socket { /* Attempt to connect to the remote host */ try { result = sock.connect(new InetSocketAddress(addr, port)); - } catch(java.io.IOException e) { - throw new SocketException("unable to connect:"+e.getMessage()); - } - - if (!result && sock.isConnectionPending()) { - while (!result) { - try { - result = sock.finishConnect(); - } catch(java.io.IOException e) { - throw new Exception(e.getMessage()); + Selector selector = Selector.open(); + SelectionKey connect_key = + sock.socket().getChannel().register(selector, SelectionKey.OP_CONNECT); + // Try for the connection for 250ms + while (selector.select(250) > 0) { + while (!result) { + + Set keys = selector.selectedKeys(); + Iterator i = keys.iterator(); + + while (i.hasNext()) { + SelectionKey key = (SelectionKey)i.next(); + + // Remove the current key + i.remove(); + + // Attempt a connection + if (key.isConnectable()) { + if (sock.isConnectionPending()) + sock.finishConnect(); + result = true; + } + } } } + if (!result) + throw new SocketException("unable to connect to socket: Host is down"); + } catch(java.io.IOException e) { + throw new SocketException("unable to connect:"+e.getMessage()); } - if (!result) - throw new SocketException("unable connect to socket"); - // Disable Nagle's algorithm, to reduce latency enableNagles(sock, false); -- 2.39.5