diff --git a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java index 8482ce25e..c94aca507 100644 --- a/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java +++ b/lib/src/main/java/io/ably/lib/transport/ConnectionManager.java @@ -162,10 +162,11 @@ public String getHost() { public void connect() { boolean connectionExist = state.state == ConnectionState.connected; - boolean connectionAttemptAvailable = (requestedState != null && requestedState.state != ConnectionState.connecting) || + boolean connectionAttemptInProgress = (requestedState != null && requestedState.state == ConnectionState.connecting) || state.state == ConnectionState.connecting; - if(!connectionExist && !connectionAttemptAvailable && startThread()) { + if(!connectionExist && !connectionAttemptInProgress) { + startThread(); // Start thread if not already started. requestState(ConnectionState.connecting); } } diff --git a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeConnectFailTest.java b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeConnectFailTest.java index cf9377064..b80e9ca1f 100644 --- a/lib/src/test/java/io/ably/lib/test/realtime/RealtimeConnectFailTest.java +++ b/lib/src/test/java/io/ably/lib/test/realtime/RealtimeConnectFailTest.java @@ -124,6 +124,38 @@ public void connect_fail_suspended() { } } + /** + * Verify that the connection in the disconnected state (after attempts to + * connect to a non-existent ws host) allows an immediate explicit connect + * attempt, instead of ignoring the explicit connect and waiting till the + * next scheduled retry. + */ + @Test + public void connect_while_disconnected() { + try { + TestVars testVars = Setup.getTestVars(); + ClientOptions opts = testVars.createOptions(testVars.keys[0].keyStr); + opts.realtimeHost = "non.existent.host"; + AblyRealtime ably = new AblyRealtime(opts); + ConnectionWaiter connectionWaiter = new ConnectionWaiter(ably.connection); + + connectionWaiter.waitFor(ConnectionState.disconnected); + assertEquals("Verify disconnected state is reached", ConnectionState.disconnected, ably.connection.state); + + long before = System.currentTimeMillis(); + ably.connection.connect(); + connectionWaiter.waitFor(ConnectionState.connecting); + assertTrue("Verify explicit connect is actioned immediately", System.currentTimeMillis() - before < 1000L); + + ably.close(); + connectionWaiter.waitFor(ConnectionState.closed); + assertEquals("Verify closed state is reached", ConnectionState.closed, ably.connection.state); + } catch (AblyException e) { + e.printStackTrace(); + fail("init0: Unexpected exception instantiating library"); + } + } + /** * Verify that the connection enters the disconnected state, after a token * used for successful connection expires