From 28beabf258c7a982938384fb01e33bf8a163330f Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Sat, 1 Aug 2020 14:35:14 +0200 Subject: [PATCH] Ignore multiple reconnects --- .../gotify/service/WebSocketConnection.java | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/github/gotify/service/WebSocketConnection.java b/app/src/main/java/com/github/gotify/service/WebSocketConnection.java index e8ed1c2..2810128 100644 --- a/app/src/main/java/com/github/gotify/service/WebSocketConnection.java +++ b/app/src/main/java/com/github/gotify/service/WebSocketConnection.java @@ -40,7 +40,7 @@ class WebSocketConnection { private BadRequestRunnable onBadRequest; private OnNetworkFailureRunnable onNetworkFailure; private Runnable onReconnected; - private boolean isClosed; + private State state; private Runnable onDisconnect; WebSocketConnection( @@ -110,8 +110,11 @@ class WebSocketConnection { } public synchronized WebSocketConnection start() { + if (state == State.Connecting || state == State.Connected) { + return this; + } close(); - isClosed = false; + state = State.Connecting; long nextId = ID.incrementAndGet(); Log.i("WebSocket(" + nextId + "): starting..."); @@ -122,13 +125,18 @@ class WebSocketConnection { public synchronized void close() { if (webSocket != null) { Log.i("WebSocket(" + ID.get() + "): closing existing connection."); - isClosed = true; + state = State.Disconnected; webSocket.close(1000, ""); webSocket = null; } } public synchronized void scheduleReconnect(long seconds) { + if (state == State.Connecting || state == State.Connected) { + return; + } + state = State.Scheduled; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Log.i( "WebSocket: scheduling a restart in " @@ -160,6 +168,7 @@ class WebSocketConnection { public void onOpen(WebSocket webSocket, Response response) { syncExec( () -> { + state = State.Connected; Log.i("WebSocket(" + id + "): opened"); onOpen.run(); @@ -186,11 +195,11 @@ class WebSocketConnection { public void onClosed(WebSocket webSocket, int code, String reason) { syncExec( () -> { - if (!isClosed) { + if (state == State.Connected) { Log.w("WebSocket(" + id + "): closed"); onClose.run(); - isClosed = true; } + state = State.Disconnected; }); super.onClosed(webSocket, code, reason); @@ -203,6 +212,7 @@ class WebSocketConnection { Log.e("WebSocket(" + id + "): failure " + code + " Message: " + message, t); syncExec( () -> { + state = State.Disconnected; if (response != null && response.code() >= 400 && response.code() <= 499) { onBadRequest.execute(message); close(); @@ -243,4 +253,11 @@ class WebSocketConnection { interface OnNetworkFailureRunnable { void execute(long millis); } + + enum State { + Scheduled, + Connecting, + Connected, + Disconnected + } }