Downed hosts should timeout reasonably quickly
diff --git a/java/com/tigervnc/network/TcpSocket.java b/java/com/tigervnc/network/TcpSocket.java
index 43787e4..95f16d3 100644
--- a/java/com/tigervnc/network/TcpSocket.java
+++ b/java/com/tigervnc/network/TcpSocket.java
@@ -32,6 +32,9 @@
 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 @@
     /* Attempt to connect to the remote host */
     try {
       result = sock.connect(new InetSocketAddress(addr, port));
+      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 && sock.isConnectionPending()) {
-      while (!result) {
-        try {
-          result = sock.finishConnect();
-        } catch(java.io.IOException e) {
-          throw new Exception(e.getMessage());
-        }
-      }
-    }
-
-    if (!result)
-      throw new SocketException("unable connect to socket");
-
     // Disable Nagle's algorithm, to reduce latency
     enableNagles(sock, false);