Send service info on WebSocket connect
This commit is contained in:
@@ -17,14 +17,16 @@ public sealed class WebSocketServerService : IDisposable
|
||||
|
||||
private readonly TimeSpan heartbeatInterval = TimeSpan.FromSeconds(5);
|
||||
private readonly SyncMessageHandler messageHandler;
|
||||
private readonly string deviceName;
|
||||
private readonly List<IWebSocketConnection> clients = [];
|
||||
private readonly object clientsLock = new();
|
||||
private WebSocketServer? server;
|
||||
private System.Threading.Timer? heartbeatTimer;
|
||||
|
||||
public WebSocketServerService(SyncMessageHandler messageHandler)
|
||||
public WebSocketServerService(SyncMessageHandler messageHandler, string? deviceName = null)
|
||||
{
|
||||
this.messageHandler = messageHandler;
|
||||
this.deviceName = string.IsNullOrWhiteSpace(deviceName) ? Environment.MachineName : deviceName;
|
||||
}
|
||||
|
||||
public int Port { get; private set; } = 8181;
|
||||
@@ -45,6 +47,18 @@ public sealed class WebSocketServerService : IDisposable
|
||||
|
||||
public event EventHandler? StatusChanged;
|
||||
|
||||
public string BuildServiceInfoJson()
|
||||
{
|
||||
return JsonSerializer.Serialize(
|
||||
new ServiceInfoMessage(
|
||||
DiscoveryResponderService.ServiceResponseType,
|
||||
1,
|
||||
deviceName,
|
||||
LocalIpAddress,
|
||||
Port),
|
||||
JsonOptions);
|
||||
}
|
||||
|
||||
public void Start(int port)
|
||||
{
|
||||
Port = port;
|
||||
@@ -72,6 +86,7 @@ public sealed class WebSocketServerService : IDisposable
|
||||
}
|
||||
|
||||
AppLogger.Info($"Client connected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
|
||||
_ = SendServiceInfoAsync(socket);
|
||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||
};
|
||||
socket.OnClose = () =>
|
||||
@@ -155,6 +170,19 @@ public sealed class WebSocketServerService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendServiceInfoAsync(IWebSocketConnection client)
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.Send(BuildServiceInfoJson());
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppLogger.Error("Failed to send WebSocket service info.", exception);
|
||||
RemoveClient(client, "service info failure");
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveClient(IWebSocketConnection client, string reason)
|
||||
{
|
||||
var removed = false;
|
||||
@@ -215,4 +243,6 @@ public sealed class WebSocketServerService : IDisposable
|
||||
|
||||
return address?.ToString() ?? "127.0.0.1";
|
||||
}
|
||||
|
||||
private sealed record ServiceInfoMessage(string Type, int Version, string Name, string Host, int Port);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user