aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--java/com/tigervnc/network/TcpSocket.java43
1 files 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);