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 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 01:30:14 +00:00
co-authored by Claude Opus 5.5
parent b7a5828c43
commit 13c1e8a659
6 changed files with 230 additions and 5 deletions
@@ -78,6 +78,9 @@ public final class TeamspeakConnection implements TS3Listener {
/** The protocol's reason ids for the two flavours of <b>clientkick</b>. */ /** The protocol's reason ids for the two flavours of <b>clientkick</b>. */
private static final int REASON_KICK_CHANNEL = 4; private static final int REASON_KICK_CHANNEL = 4;
private static final int REASON_KICK_SERVER = 5; 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_CLIENT_INSUFFICIENT = 0x0a08;
private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09;
@@ -170,6 +173,8 @@ public final class TeamspeakConnection implements TS3Listener {
private volatile long lastMutedTalkNanos; private volatile long lastMutedTalkNanos;
/** The server's error id for why the last connect was refused; 0 when it was not. */ /** The server's error id for why the last connect was refused; 0 when it was not. */
private volatile int connectErrorId; 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 MyTeamSpeakLogin myTeamSpeak;
private volatile boolean myTeamSpeakFeatures = true; private volatile boolean myTeamSpeakFeatures = true;
private final Object myTeamSpeakUpdateLock = new Object(); private final Object myTeamSpeakUpdateLock = new Object();
@@ -255,6 +260,15 @@ public final class TeamspeakConnection implements TS3Listener {
return connectErrorId; 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. */ /** The identity this connection authenticated with. */
public LocalIdentity getIdentity() { public LocalIdentity getIdentity() {
return identity; return identity;
@@ -332,6 +346,7 @@ public final class TeamspeakConnection implements TS3Listener {
Object attempt = new Object(); Object attempt = new Object();
connectAttempt = attempt; connectAttempt = attempt;
connectErrorId = 0; connectErrorId = 0;
disconnectReasonId = -1;
// A socket or audio line an earlier connect left behind must not outlive it. // A socket or audio line an earlier connect left behind must not outlive it.
connected = false; connected = false;
safeCleanup(); safeCleanup();
@@ -608,6 +623,7 @@ public final class TeamspeakConnection implements TS3Listener {
public void disconnectBlocking(String reason) { public void disconnectBlocking(String reason) {
connectAttempt = null; connectAttempt = null;
leaving = true; leaving = true;
disconnectReasonId = -1;
try { try {
if (client != null) client.disconnect(reason); if (client != null) client.disconnect(reason);
} catch (Exception ignored) { } catch (Exception ignored) {
@@ -1891,6 +1907,7 @@ public final class TeamspeakConnection implements TS3Listener {
@Override @Override
public void onDisconnected(DisconnectedEvent e) { public void onDisconnected(DisconnectedEvent e) {
connected = false; connected = false;
disconnectReasonId = e.getReasonId();
safeCleanup(); safeCleanup();
announceDisconnect(false); announceDisconnect(false);
String reason = orEmpty(e.getReasonMessage()); String reason = orEmpty(e.getReasonMessage());
@@ -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;
}
}
@@ -71,6 +71,7 @@ public final class ServerSession {
private final IdentityStore identities; private final IdentityStore identities;
private final Listener listener; private final Listener listener;
private final TeamspeakConnection conn; private final TeamspeakConnection conn;
private final AutoReconnect reconnects = new AutoReconnect(this);
private volatile String title = "New connection"; private volatile String title = "New connection";
private volatile String status = "Not connected"; private volatile String status = "Not connected";
@@ -118,8 +119,10 @@ public final class ServerSession {
return title; return title;
} }
/** What the connection is up to, or the countdown to the next reconnect. */
public String status() { public String status() {
return status; int wait = reconnects.secondsLeft();
return wait > 0 ? "Reconnecting in " + wait + " s…" : status;
} }
public boolean isConnected() { public boolean isConnected() {
@@ -168,10 +171,17 @@ public final class ServerSession {
*/ */
public void connect(String address, int port, String nickname, String password, String identityId, public void connect(String address, int port, String nickname, String password, String identityId,
String channel, String channelPassword) { String channel, String channelPassword) {
reconnects.cancel();
synchronized (this) { synchronized (this) {
if (isBusy()) return; if (isBusy()) return;
connecting = true; 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); lastTarget = new Target(address, port, nickname, password, channelPassword);
lastChannelPath = channel == null ? "" : channel; lastChannelPath = channel == null ? "" : channel;
title = address + ":" + port; title = address + ":" + port;
@@ -187,6 +197,7 @@ public final class ServerSession {
} catch (Exception e) { } catch (Exception e) {
connecting = false; connecting = false;
reportError("Could not load identity: " + e.getMessage()); reportError("Could not load identity: " + e.getMessage());
reconnects.disconnected(false, 0);
return; return;
} }
this.identityId = entry.getId(); 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, public void switchTo(String address, int port, String nickname, String password, String identityId,
String channel, String channelPassword) { String channel, String channelPassword) {
reconnects.cancel();
if (!isBusy()) { if (!isBusy()) {
connect(address, port, nickname, password, identityId, channel, channelPassword); connect(address, port, nickname, password, identityId, channel, channelPassword);
return; return;
@@ -255,13 +267,53 @@ public final class ServerSession {
channel, target.channelPassword()); 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. */ /** Leaves the server, or gives up a connect that is still under way. */
public void disconnect() { public void disconnect() {
reconnects.cancel();
if (isBusy()) conn.disconnect(); if (isBusy()) conn.disconnect();
} }
/** Synchronous teardown for shutdown paths, so the server sees us leave and recordings are written. */ /** Synchronous teardown for shutdown paths, so the server sees us leave and recordings are written. */
public void shutdown() { public void shutdown() {
reconnects.cancel();
CompletableFuture<List<Path>> recording = conn.stopRecording(false); CompletableFuture<List<Path>> recording = conn.stopRecording(false);
if (isBusy()) conn.disconnectBlocking("Leaving"); if (isBusy()) conn.disconnectBlocking("Leaving");
if (recording != null) { if (recording != null) {
@@ -296,6 +348,7 @@ public final class ServerSession {
/** Releases the background resources of a session that is being thrown away. */ /** Releases the background resources of a session that is being thrown away. */
public void dispose() { public void dispose() {
reconnects.setEnabled(false);
conn.getIcons().shutdown(); conn.getIcons().shutdown();
} }
@@ -775,6 +828,7 @@ public final class ServerSession {
@Override @Override
public void onConnected() { public void onConnected() {
connecting = false; connecting = false;
reconnects.connected();
resetSelfState(); resetSelfState();
listener.onConnected(); listener.onConnected();
listener.onSystemMessage("Connected."); listener.onSystemMessage("Connected.");
@@ -793,6 +847,7 @@ public final class ServerSession {
conn.getModel().clear(); conn.getModel().clear();
listener.onDisconnected(reason); listener.onDisconnected(reason);
listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason));
reconnects.disconnected(conn.wasDropped(), conn.getConnectErrorId());
listener.onSessionChanged(); listener.onSessionChanged();
} }
@@ -181,6 +181,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
if (selected != null) selected.session().stopRecording(); if (selected != null) selected.session().stopRecording();
}, () -> { }, () -> {
if (selected != null) selected.showOfflineMessages(); if (selected != null) selected.showOfflineMessages();
}, () -> {
if (selected != null) selected.session().cancelReconnect();
}); });
statusBar.setVisible(settings.showStatusBar); statusBar.setVisible(settings.showStatusBar);
add(statusBar, BorderLayout.SOUTH); add(statusBar, BorderLayout.SOUTH);
@@ -1171,6 +1173,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
private void updateStatusLabel() { private void updateStatusLabel() {
statusBar.setStatus(selected == null ? "Not connected" : selected.session().status()); statusBar.setStatus(selected == null ? "Not connected" : selected.session().status());
statusBar.showReconnecting(selected != null && selected.session().isReconnecting());
} }
private void updateConnectionStatus() { private void updateConnectionStatus() {
@@ -74,6 +74,7 @@ final class ServerTab {
ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings); ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings);
this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); this.session = new ServerSession(settings, identities, audio, sounds, contacts, events);
this.conn = session.connection(); this.conn = session.connection();
session.setAutoReconnect(true);
this.conn.setMyTeamSpeakLogin(host.myTeamSpeakLogin()); this.conn.setMyTeamSpeakLogin(host.myTeamSpeakLogin());
this.groupIcons = new GroupIcons(conn.getIcons()); this.groupIcons = new GroupIcons(conn.getIcons());
this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId); this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId);
@@ -3,10 +3,13 @@ package eu.lixko.ts3j.client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale; import com.formdev.flatlaf.util.UIScale;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JPanel; import javax.swing.JPanel;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Cursor; import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout; import java.awt.FlowLayout;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; 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 * 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 * 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 { final class StatusBar extends JPanel {
@@ -22,8 +26,9 @@ final class StatusBar extends JPanel {
private final JLabel codecLabel = new JLabel(); private final JLabel codecLabel = new JLabel();
private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING); 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 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()); super(new BorderLayout());
setBackground(Theme.statusBg()); setBackground(Theme.statusBg());
setBorder(new ScaledEmptyBorder(3, 8, 3, 8)); setBorder(new ScaledEmptyBorder(3, 8, 3, 8));
@@ -48,13 +53,31 @@ final class StatusBar extends JPanel {
onOpenOfflineMessages.run(); 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)); JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0));
east.setOpaque(false); east.setOpaque(false);
east.add(unreadLabel); east.add(unreadLabel);
east.add(recordingLabel); east.add(recordingLabel);
east.add(codecLabel); east.add(codecLabel);
// In the centre, a long status is cut short rather than drawn over the labels beside it. // A long status is cut short rather than drawn over the labels beside it.
add(statusLabel, BorderLayout.CENTER); 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); add(east, BorderLayout.EAST);
} }
@@ -72,6 +95,10 @@ final class StatusBar extends JPanel {
statusLabel.setText(text); statusLabel.setText(text);
} }
void showReconnecting(boolean reconnecting) {
cancelReconnectLabel.setVisible(reconnecting);
}
void setCodec(String text) { void setCodec(String text) {
codecLabel.setText(text); codecLabel.setText(text);
} }