Add WebSocket heartbeat, client cleanup, and connection toast notifications

- Add heartbeat ping every 5 seconds to detect stale connections
- Replace clients when same IP reconnects instead of accumulating
- Remove unavailable clients on connect and heartbeat probe
- Marshal UI updates to UI thread via SynchronizationContext
- Show balloon toast on device connect/disconnect
- Add disposal safety check for UpdateTrayStatus

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Misaka
2026-05-17 12:34:02 +08:00
parent 32ef8fb1ac
commit cbbadd547d
2 changed files with 105 additions and 2 deletions

View File

@@ -9,15 +9,18 @@ namespace WirelessTextSyncer.Windows.Services;
public sealed class WebSocketServerService : IDisposable
{
private static readonly byte[] HeartbeatPayload = "wts-heartbeat"u8.ToArray();
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true
};
private readonly TimeSpan heartbeatInterval = TimeSpan.FromSeconds(5);
private readonly SyncMessageHandler messageHandler;
private readonly List<IWebSocketConnection> clients = [];
private readonly object clientsLock = new();
private WebSocketServer? server;
private System.Threading.Timer? heartbeatTimer;
public WebSocketServerService(SyncMessageHandler messageHandler)
{
@@ -34,6 +37,7 @@ public sealed class WebSocketServerService : IDisposable
{
lock (clientsLock)
{
clients.RemoveAll(client => !client.IsAvailable);
return clients.Count > 0;
}
}
@@ -52,11 +56,21 @@ public sealed class WebSocketServerService : IDisposable
{
socket.OnOpen = () =>
{
IWebSocketConnection[] replacedClients;
lock (clientsLock)
{
replacedClients = clients
.Where(client => client.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress)
.ToArray();
clients.RemoveAll(client => !client.IsAvailable || replacedClients.Contains(client));
clients.Add(socket);
}
foreach (var replacedClient in replacedClients)
{
replacedClient.Close();
}
AppLogger.Info($"Client connected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
StatusChanged?.Invoke(this, EventArgs.Empty);
};
@@ -73,14 +87,16 @@ public sealed class WebSocketServerService : IDisposable
socket.OnError = exception =>
{
AppLogger.Error("WebSocket connection error.", exception);
StatusChanged?.Invoke(this, EventArgs.Empty);
RemoveClient(socket, "connection error");
};
socket.OnMessage = HandleRawMessage;
});
heartbeatTimer = new System.Threading.Timer(_ => ProbeClients(), null, heartbeatInterval, heartbeatInterval);
}
public void Dispose()
{
heartbeatTimer?.Dispose();
IWebSocketConnection[] currentClients;
lock (clientsLock)
{
@@ -96,6 +112,66 @@ public sealed class WebSocketServerService : IDisposable
server?.Dispose();
}
private void ProbeClients()
{
IWebSocketConnection[] currentClients;
var removedUnavailableClients = false;
lock (clientsLock)
{
var countBefore = clients.Count;
clients.RemoveAll(client => !client.IsAvailable);
removedUnavailableClients = clients.Count != countBefore;
currentClients = clients.ToArray();
}
if (removedUnavailableClients)
{
AppLogger.Info("Removed unavailable WebSocket clients during heartbeat.");
StatusChanged?.Invoke(this, EventArgs.Empty);
}
foreach (var client in currentClients)
{
_ = SendHeartbeatAsync(client);
}
}
private async Task SendHeartbeatAsync(IWebSocketConnection client)
{
try
{
if (!client.IsAvailable)
{
RemoveClient(client, "heartbeat unavailable");
return;
}
await client.SendPing(HeartbeatPayload);
}
catch (Exception exception)
{
AppLogger.Error("WebSocket heartbeat failed.", exception);
RemoveClient(client, "heartbeat failure");
}
}
private void RemoveClient(IWebSocketConnection client, string reason)
{
var removed = false;
lock (clientsLock)
{
removed = clients.Remove(client);
}
if (!removed)
{
return;
}
AppLogger.Info($"Removed WebSocket client after {reason}: {client.ConnectionInfo.ClientIpAddress}:{client.ConnectionInfo.ClientPort}");
StatusChanged?.Invoke(this, EventArgs.Empty);
}
private void HandleRawMessage(string rawMessage)
{
try