From 87b9ffcc3702268596b0d2bc9befb6182cca6360 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Mon, 20 Mar 2023 23:10:52 +0100 Subject: [PATCH] Another websocket client fix: the socket reference is not set soon enough + add some more error handling --- .../lib/ws/client/AbstractClientWS.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/pandalib-ws-client/src/main/java/fr/pandacube/lib/ws/client/AbstractClientWS.java b/pandalib-ws-client/src/main/java/fr/pandacube/lib/ws/client/AbstractClientWS.java index 16ff2a7..ce300d5 100644 --- a/pandalib-ws-client/src/main/java/fr/pandacube/lib/ws/client/AbstractClientWS.java +++ b/pandalib-ws-client/src/main/java/fr/pandacube/lib/ws/client/AbstractClientWS.java @@ -29,19 +29,37 @@ public abstract class AbstractClientWS implements AbstractWS { private final Listener receiveListener = new Listener() { @Override public void onOpen(WebSocket webSocket) { - AbstractClientWS.this.onConnect(); + // this method is actually called before the CompletableFuture from the WS Builder is completed, so + // we have to affect socket reference before doing anything + synchronized (socket) { + socket.set(webSocket); + isConnecting = false; + } + try { + AbstractClientWS.this.onConnect(); + } catch (Exception e) { + logError("Error handling connection opening.", e); + } Listener.super.onOpen(webSocket); } @Override public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean last) { - AbstractClientWS.this.handleReceivedMessage(data.toString()); + try { + AbstractClientWS.this.handleReceivedMessage(data.toString()); + } catch (Exception e) { + logError("Error handling reception of text.", e); + } return Listener.super.onText(webSocket, data, last); } @Override public CompletionStage onBinary(WebSocket webSocket, ByteBuffer data, boolean last) { - AbstractClientWS.this.handleReceivedBinary(); + try { + AbstractClientWS.this.handleReceivedBinary(); + } catch (Exception e) { + logError("Error handling reception of binary.", e); + } return Listener.super.onBinary(webSocket, data, last); } @@ -105,6 +123,8 @@ public abstract class AbstractClientWS implements AbstractWS { synchronized (socket) { isConnecting = false; if (ws != null) { + // the value may already been set by the onOpen method of the receiveListener + // but just in case, we do it here too socket.set(ws); return; }