Do not put the HttpClient of a persistent websocket into a try-with-resources

This commit is contained in:
Marc Baloup 2025-01-19 23:30:56 +01:00
parent 51bc0bd6e8
commit f4d0ccca51

View File

@ -23,6 +23,7 @@ public abstract class AbstractClientWS implements AbstractWS {
private final URI uri; private final URI uri;
private boolean autoReconnect; private boolean autoReconnect;
private boolean isConnecting; private boolean isConnecting;
private HttpClient httpClient = HttpClient.newHttpClient();
private final AtomicReference<WebSocket> socket = new AtomicReference<>(); private final AtomicReference<WebSocket> socket = new AtomicReference<>();
@ -127,32 +128,33 @@ public abstract class AbstractClientWS implements AbstractWS {
private void connect() { private void connect() {
synchronized (socket) { synchronized (socket) {
isConnecting = true; isConnecting = true;
try (HttpClient cl = HttpClient.newHttpClient()) { if (httpClient == null)
cl.newWebSocketBuilder() httpClient = HttpClient.newHttpClient();
.connectTimeout(Duration.ofSeconds(5))
.buildAsync(uri, receiveListener) httpClient.newWebSocketBuilder()
.whenCompleteAsync((ws, ex) -> { .connectTimeout(Duration.ofSeconds(5))
synchronized (socket) { .buildAsync(uri, receiveListener)
isConnecting = false; .whenCompleteAsync((ws, ex) -> {
if (ws != null) { synchronized (socket) {
// the value may already been set by the onOpen method of the receiveListener isConnecting = false;
// but just in case, we do it here too if (ws != null) {
socket.set(ws); // the value may already been set by the onOpen method of the receiveListener
return; // but just in case, we do it here too
} socket.set(ws);
return;
} }
if (ex instanceof CompletionException) }
ex = ex.getCause(); if (ex instanceof CompletionException)
if (ex instanceof IOException) { ex = ex.getCause();
reconnectIfNecessary(); if (ex instanceof IOException) {
log("Unable to connect. Trying again...: " + ex); reconnectIfNecessary();
} log("Unable to connect. Trying again...: " + ex);
else { }
autoReconnect = false; else {
logError("Error connecting (not trying to reconnect even if asked)", ex); autoReconnect = false;
} logError("Error connecting (not trying to reconnect even if asked)", ex);
}); }
} });
} }