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,8 +128,10 @@ 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();
httpClient.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(5)) .connectTimeout(Duration.ofSeconds(5))
.buildAsync(uri, receiveListener) .buildAsync(uri, receiveListener)
.whenCompleteAsync((ws, ex) -> { .whenCompleteAsync((ws, ex) -> {
@ -152,7 +155,6 @@ public abstract class AbstractClientWS implements AbstractWS {
logError("Error connecting (not trying to reconnect even if asked)", ex); logError("Error connecting (not trying to reconnect even if asked)", ex);
} }
}); });
}
} }