From 13c1e8a6597a5a882e35811a1067ad02e6863d00 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Sun, 11 Oct 2026 01:30:14 +0000 Subject: [PATCH] Reconnect on desktop after a dropped connection After a timeout or a server shutdown the session counts down and connects again, back to the channel it was in, waiting 5, 10, 20, 40 and then 60 s between attempts. A kick, a ban, leaving, or connecting elsewhere ends it, as does a retry refused with a ban. The status bar shows the countdown with a Cancel link. Off by default in core, so Android keeps its own NetworkFollower. Co-Authored-By: Claude Opus 5.5 --- .../ts3j/client/net/TeamspeakConnection.java | 17 +++ .../ts3j/client/session/AutoReconnect.java | 122 ++++++++++++++++++ .../ts3j/client/session/ServerSession.java | 57 +++++++- .../eu/lixko/ts3j/client/ui/MainFrame.java | 3 + .../eu/lixko/ts3j/client/ui/ServerTab.java | 1 + .../eu/lixko/ts3j/client/ui/StatusBar.java | 35 ++++- 6 files changed, 230 insertions(+), 5 deletions(-) create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/AutoReconnect.java diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java index 3b25c40..f32a985 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -78,6 +78,9 @@ public final class TeamspeakConnection implements TS3Listener { /** The protocol's reason ids for the two flavours of clientkick. */ private static final int REASON_KICK_CHANNEL = 4; private static final int REASON_KICK_SERVER = 5; + /** The reason ids of our own leaving that nobody chose: timing out, the server going down. */ + private static final int REASON_CONNECTION_LOST = 3; + private static final int REASON_SERVER_SHUTDOWN = 11; private static final int ERROR_PERMISSIONS_CLIENT_INSUFFICIENT = 0x0a08; private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; @@ -170,6 +173,8 @@ public final class TeamspeakConnection implements TS3Listener { private volatile long lastMutedTalkNanos; /** The server's error id for why the last connect was refused; 0 when it was not. */ private volatile int connectErrorId; + /** The server's {@code reasonid} for how the last connection ended; -1 when we left or never got on. */ + private volatile int disconnectReasonId = -1; private volatile MyTeamSpeakLogin myTeamSpeak; private volatile boolean myTeamSpeakFeatures = true; private final Object myTeamSpeakUpdateLock = new Object(); @@ -255,6 +260,15 @@ public final class TeamspeakConnection implements TS3Listener { return connectErrorId; } + /** + * Whether the last connection ended without anyone meaning it to: it timed out, or the + * server shut down. Not after a kick, a ban, leaving on purpose or a refused connect. + */ + public boolean wasDropped() { + int reason = disconnectReasonId; + return reason == REASON_CONNECTION_LOST || reason == REASON_SERVER_SHUTDOWN; + } + /** The identity this connection authenticated with. */ public LocalIdentity getIdentity() { return identity; @@ -332,6 +346,7 @@ public final class TeamspeakConnection implements TS3Listener { Object attempt = new Object(); connectAttempt = attempt; connectErrorId = 0; + disconnectReasonId = -1; // A socket or audio line an earlier connect left behind must not outlive it. connected = false; safeCleanup(); @@ -608,6 +623,7 @@ public final class TeamspeakConnection implements TS3Listener { public void disconnectBlocking(String reason) { connectAttempt = null; leaving = true; + disconnectReasonId = -1; try { if (client != null) client.disconnect(reason); } catch (Exception ignored) { @@ -1891,6 +1907,7 @@ public final class TeamspeakConnection implements TS3Listener { @Override public void onDisconnected(DisconnectedEvent e) { connected = false; + disconnectReasonId = e.getReasonId(); safeCleanup(); announceDisconnect(false); String reason = orEmpty(e.getReasonMessage()); diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/AutoReconnect.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/AutoReconnect.java new file mode 100644 index 0000000..27ccb31 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/AutoReconnect.java @@ -0,0 +1,122 @@ +package eu.lixko.ts3j.client.session; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +/** + * Gets a {@link ServerSession} back on its server after the connection drops underneath it: + * a timeout, or the server going down for a restart. Counts down to each attempt, waiting + * longer after every failed one, and gives up at a ban. A kick or a ban, leaving, or + * connecting anywhere else ends it. + */ +final class AutoReconnect { + + /** The server's refusal for a banned client; asking again will not help. */ + private static final int ERROR_BANNED = 3329; + private static final int[] DELAYS_S = {5, 10, 20, 40, 60}; + + private static final ScheduledExecutorService TIMER = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "ts3-reconnect"); + t.setDaemon(true); + return t; + }); + + private final ServerSession session; + + private boolean enabled; + /** Failed attempts since the connection dropped, for the backoff. */ + private int failures; + private int secondsLeft; + private ScheduledFuture countdown; + /** An attempt is under way: the session is connecting on our behalf. */ + private boolean attempting; + + AutoReconnect(ServerSession session) { + this.session = session; + } + + synchronized void setEnabled(boolean enabled) { + this.enabled = enabled; + if (!enabled) stop(); + } + + /** Waiting for the next attempt, or in the middle of one. */ + synchronized boolean isActive() { + return countdown != null || attempting; + } + + synchronized boolean isAttempting() { + return attempting; + } + + /** Seconds until the next attempt; 0 when none is counting down. */ + synchronized int secondsLeft() { + return countdown != null ? secondsLeft : 0; + } + + /** @return whether there was anything to cancel */ + boolean cancel() { + synchronized (this) { + if (!isActive()) return false; + stop(); + } + session.reconnectChanged(); + return true; + } + + void connected() { + synchronized (this) { + stop(); + } + } + + /** + * @param dropped what {@link eu.lixko.ts3j.client.net.TeamspeakConnection#wasDropped} says + * @param refusal the error id a refused connect carried, else 0 + */ + void disconnected(boolean dropped, int refusal) { + synchronized (this) { + if (!enabled) return; + if (attempting) { + attempting = false; + if (refusal == ERROR_BANNED) { + stop(); + return; + } + } else if (dropped) { + failures = 0; + } else { + return; + } + secondsLeft = DELAYS_S[Math.min(failures, DELAYS_S.length - 1)]; + failures++; + if (countdown != null) countdown.cancel(false); + countdown = TIMER.scheduleAtFixedRate(this::tick, 1, 1, TimeUnit.SECONDS); + } + session.reconnectChanged(); + } + + private void tick() { + boolean due; + synchronized (this) { + if (countdown == null) return; + due = --secondsLeft <= 0; + if (due) { + countdown.cancel(false); + countdown = null; + attempting = true; + } + } + if (due) session.retryConnect(); + else session.reconnectChanged(); + } + + private void stop() { + if (countdown != null) countdown.cancel(false); + countdown = null; + attempting = false; + failures = 0; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java index 836584d..a1b6c42 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -71,6 +71,7 @@ public final class ServerSession { private final IdentityStore identities; private final Listener listener; private final TeamspeakConnection conn; + private final AutoReconnect reconnects = new AutoReconnect(this); private volatile String title = "New connection"; private volatile String status = "Not connected"; @@ -118,8 +119,10 @@ public final class ServerSession { return title; } + /** What the connection is up to, or the countdown to the next reconnect. */ public String status() { - return status; + int wait = reconnects.secondsLeft(); + return wait > 0 ? "Reconnecting in " + wait + " s…" : status; } public boolean isConnected() { @@ -168,10 +171,17 @@ public final class ServerSession { */ public void connect(String address, int port, String nickname, String password, String identityId, String channel, String channelPassword) { + reconnects.cancel(); synchronized (this) { if (isBusy()) return; connecting = true; } + begin(address, port, nickname, password, identityId, channel, channelPassword); + } + + /** Connects once {@link #connecting} has been claimed. */ + private void begin(String address, int port, String nickname, String password, String identityId, + String channel, String channelPassword) { lastTarget = new Target(address, port, nickname, password, channelPassword); lastChannelPath = channel == null ? "" : channel; title = address + ":" + port; @@ -187,6 +197,7 @@ public final class ServerSession { } catch (Exception e) { connecting = false; reportError("Could not load identity: " + e.getMessage()); + reconnects.disconnected(false, 0); return; } this.identityId = entry.getId(); @@ -231,6 +242,7 @@ public final class ServerSession { */ public void switchTo(String address, int port, String nickname, String password, String identityId, String channel, String channelPassword) { + reconnects.cancel(); if (!isBusy()) { connect(address, port, nickname, password, identityId, channel, channelPassword); return; @@ -255,13 +267,53 @@ public final class ServerSession { channel, target.channelPassword()); } + /** + * Connects again on its own after the connection drops (a timeout, a server restart), + * with longer waits after each failed attempt. Off by default, for frontends that + * follow the network themselves. + */ + public void setAutoReconnect(boolean enabled) { + reconnects.setEnabled(enabled); + } + + /** Counting down to a reconnect, or in the middle of one. */ + public boolean isReconnecting() { + return reconnects.isActive(); + } + + /** Stops reconnecting, giving up an attempt that is under way. */ + public void cancelReconnect() { + boolean attempting = reconnects.isAttempting(); + if (reconnects.cancel() && attempting && isBusy()) conn.disconnect(); + } + + /** An {@link AutoReconnect} attempt: the last connect again, unless something else took the session. */ + void retryConnect() { + Target target = lastTarget; + synchronized (this) { + if (target == null || isBusy() || !reconnects.isAttempting()) { + reconnects.cancel(); + return; + } + connecting = true; + } + begin(target.address(), target.port(), target.nickname(), target.password(), identityId, + lastChannelPath, target.channelPassword()); + } + + void reconnectChanged() { + listener.onSessionChanged(); + } + /** Leaves the server, or gives up a connect that is still under way. */ public void disconnect() { + reconnects.cancel(); if (isBusy()) conn.disconnect(); } /** Synchronous teardown for shutdown paths, so the server sees us leave and recordings are written. */ public void shutdown() { + reconnects.cancel(); CompletableFuture> recording = conn.stopRecording(false); if (isBusy()) conn.disconnectBlocking("Leaving"); if (recording != null) { @@ -296,6 +348,7 @@ public final class ServerSession { /** Releases the background resources of a session that is being thrown away. */ public void dispose() { + reconnects.setEnabled(false); conn.getIcons().shutdown(); } @@ -775,6 +828,7 @@ public final class ServerSession { @Override public void onConnected() { connecting = false; + reconnects.connected(); resetSelfState(); listener.onConnected(); listener.onSystemMessage("Connected."); @@ -793,6 +847,7 @@ public final class ServerSession { conn.getModel().clear(); listener.onDisconnected(reason); listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); + reconnects.disconnected(conn.wasDropped(), conn.getConnectErrorId()); listener.onSessionChanged(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java index 697bf98..1c3eece 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java @@ -181,6 +181,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { if (selected != null) selected.session().stopRecording(); }, () -> { if (selected != null) selected.showOfflineMessages(); + }, () -> { + if (selected != null) selected.session().cancelReconnect(); }); statusBar.setVisible(settings.showStatusBar); add(statusBar, BorderLayout.SOUTH); @@ -1171,6 +1173,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { private void updateStatusLabel() { statusBar.setStatus(selected == null ? "Not connected" : selected.session().status()); + statusBar.showReconnecting(selected != null && selected.session().isReconnecting()); } private void updateConnectionStatus() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index ffaf1d5..6608208 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -74,6 +74,7 @@ final class ServerTab { ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings); this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); this.conn = session.connection(); + session.setAutoReconnect(true); this.conn.setMyTeamSpeakLogin(host.myTeamSpeakLogin()); this.groupIcons = new GroupIcons(conn.getIcons()); this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java index dfed98b..3368f9b 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java @@ -3,10 +3,13 @@ package eu.lixko.ts3j.client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; +import javax.swing.Box; +import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Cursor; +import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; @@ -14,7 +17,8 @@ import java.awt.event.MouseEvent; /** * The strip at the bottom of the window: connection status on the left, codec info on the * right, and while the server on screen is being recorded, a label that stops it. An envelope - * shows while that server holds unread offline messages for us, and opens them. + * shows while that server holds unread offline messages for us, and opens them. While that + * server's connection is being re-established, a link beside the status cancels it. */ final class StatusBar extends JPanel { @@ -22,8 +26,9 @@ final class StatusBar extends JPanel { private final JLabel codecLabel = new JLabel(); private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING); private final JLabel unreadLabel = new JLabel(Icons.of("OFFLINE_MESSAGES")); + private final JLabel cancelReconnectLabel = new JLabel("Cancel"); - StatusBar(Runnable onStopRecording, Runnable onOpenOfflineMessages) { + StatusBar(Runnable onStopRecording, Runnable onOpenOfflineMessages, Runnable onCancelReconnect) { super(new BorderLayout()); setBackground(Theme.statusBg()); setBorder(new ScaledEmptyBorder(3, 8, 3, 8)); @@ -48,13 +53,31 @@ final class StatusBar extends JPanel { onOpenOfflineMessages.run(); } }); + cancelReconnectLabel.setFont(Theme.uiFont()); + cancelReconnectLabel.setForeground(Theme.link()); + cancelReconnectLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + cancelReconnectLabel.setVisible(false); + cancelReconnectLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + onCancelReconnect.run(); + } + }); JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0)); east.setOpaque(false); east.add(unreadLabel); east.add(recordingLabel); east.add(codecLabel); - // In the centre, a long status is cut short rather than drawn over the labels beside it. - add(statusLabel, BorderLayout.CENTER); + // A long status is cut short rather than drawn over the labels beside it. + statusLabel.setMinimumSize(new Dimension(0, 0)); + JPanel west = new JPanel(); + west.setLayout(new BoxLayout(west, BoxLayout.LINE_AXIS)); + west.setOpaque(false); + west.add(statusLabel); + west.add(Box.createHorizontalStrut(UIScale.scale(8))); + west.add(cancelReconnectLabel); + west.add(Box.createHorizontalGlue()); + add(west, BorderLayout.CENTER); add(east, BorderLayout.EAST); } @@ -72,6 +95,10 @@ final class StatusBar extends JPanel { statusLabel.setText(text); } + void showReconnecting(boolean reconnecting) { + cancelReconnectLabel.setVisible(reconnecting); + } + void setCodec(String text) { codecLabel.setText(text); }