From f7d51a84cfaeb829d0edaa40c0aa0df1ad0bdf67 Mon Sep 17 00:00:00 2001 From: Cameron Auser Date: Fri, 16 Feb 2024 15:15:37 -0600 Subject: [PATCH 1/2] Explicitly close the socket when resetting the client if the connection is not yet opened. This prevents the write thread from hanging while attempting to write to the output stream. Reset the connection if we fail to connect during connectBlocking. --- .../org/java_websocket/client/WebSocketClient.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index 756534cd..d8db4725 100644 --- a/src/main/java/org/java_websocket/client/WebSocketClient.java +++ b/src/main/java/org/java_websocket/client/WebSocketClient.java @@ -339,7 +339,11 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { + if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED) { + socket.close(); + } closeBlocking(); + if (writeThread != null) { this.writeThread.interrupt(); this.writeThread.join(); @@ -401,7 +405,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(); } /** From d8eb0f8b98293c6a9dc18558b5c8cf41a58badda Mon Sep 17 00:00:00 2001 From: Cameron Auser Date: Wed, 21 Feb 2024 09:17:50 -0600 Subject: [PATCH 2/2] Ensure the socket is not null when attempting to close it. --- src/main/java/org/java_websocket/client/WebSocketClient.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java index d8db4725..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,9 @@ private void reset() { "You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to ensure a successful cleanup."); } try { - if (engine.getReadyState() == ReadyState.NOT_YET_CONNECTED) { + // 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();