diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 756534cd..18cea8a2 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -339,7 +339,13 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { + // This socket null check ensures we can reconnect a socket that failed to connect. It's an uncommon edge case, but we want to make sure we support it + if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED && socket != null) { + // Closing the socket when we have not connected prevents the writeThread from hanging on a write indefinitely during connection teardown + socket.close(); + } closeBlocking(); + if (writeThread != null) { this.writeThread.interrupt(); this.writeThread.join(); @@ -401,7 +407,13 @@ public boolean connectBlocking() throws InterruptedException { */ public boolean connectBlocking(long timeout, TimeUnit timeUnit) throws InterruptedException { connect(); - return connectLatch.await(timeout, timeUnit) && engine.isOpen(); + + boolean connected = connectLatch.await(timeout, timeUnit); + if (!connected) { + reset(); + } + + return connected && engine.isOpen(); } /**