]> source.dussan.org Git - tigervnc.git/commitdiff
Downed hosts should timeout reasonably quickly
authorBrian P. Hinz <bphinz@users.sf.net>
Mon, 20 Feb 2017 04:59:03 +0000 (23:59 -0500)
committerBrian P. Hinz <bphinz@users.sf.net>
Mon, 20 Feb 2017 05:02:45 +0000 (00:02 -0500)
java/com/tigervnc/network/TcpSocket.java

index 43787e4d3cfd004e55b7ee9ec85fc542e78f6f6b..95f16d3a1fa8b6c680d4f212ca0d287da486d22d 100644 (file)
@@ -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);