servicepoint-tanks/TanksServer/Interactivity/ClientScreenServer.cs

64 lines
2.3 KiB
C#
Raw Normal View History

2024-04-07 17:17:11 +02:00
using System.Diagnostics;
2024-04-06 16:38:26 +02:00
using System.Net.WebSockets;
using DisplayCommands;
2024-04-06 20:32:54 +02:00
using Microsoft.Extensions.Hosting;
using TanksServer.Graphics;
2024-04-06 16:38:26 +02:00
2024-04-10 19:25:45 +02:00
namespace TanksServer.Interactivity;
2024-04-06 16:38:26 +02:00
2024-04-06 20:32:54 +02:00
internal sealed class ClientScreenServer(
ILogger<ClientScreenServer> logger,
ILoggerFactory loggerFactory,
IOptions<HostConfiguration> hostConfig
) : IHostedLifecycleService, IFrameConsumer
2024-04-06 16:38:26 +02:00
{
2024-04-07 17:17:11 +02:00
private readonly ConcurrentDictionary<ClientScreenServerConnection, byte> _connections = new();
private readonly TimeSpan _minFrameTime = TimeSpan.FromMilliseconds(hostConfig.Value.ClientDisplayMinFrameTimeMs);
2024-04-07 17:17:11 +02:00
private bool _closing;
2024-04-06 16:38:26 +02:00
2024-04-13 12:33:08 +02:00
public Task StoppingAsync(CancellationToken cancellationToken)
{
logger.LogInformation("closing connections");
_closing = true;
return Task.WhenAll(_connections.Keys.Select(c => c.CloseAsync()));
}
public Task HandleClient(WebSocket socket, Guid? playerGuid)
2024-04-06 16:38:26 +02:00
{
2024-04-07 17:17:11 +02:00
if (_closing)
{
logger.LogWarning("ignoring request because connections are closing");
return Task.CompletedTask;
}
2024-04-06 20:32:54 +02:00
logger.LogDebug("HandleClient");
var connection = new ClientScreenServerConnection(
socket,
loggerFactory.CreateLogger<ClientScreenServerConnection>(),
this,
_minFrameTime,
playerGuid);
2024-04-07 17:17:11 +02:00
var added = _connections.TryAdd(connection, 0);
Debug.Assert(added);
2024-04-06 20:32:54 +02:00
return connection.Done;
2024-04-06 16:38:26 +02:00
}
public void Remove(ClientScreenServerConnection connection) => _connections.TryRemove(connection, out _);
2024-04-06 16:38:26 +02:00
2024-04-13 12:33:08 +02:00
public IEnumerable<ClientScreenServerConnection> GetConnections() => _connections.Keys;
public Task OnFrameDoneAsync(GamePixelGrid gamePixelGrid, PixelGrid observerPixels)
{
var tasks = _connections.Keys
.Select(c => c.SendAsync(observerPixels, gamePixelGrid));
return Task.WhenAll(tasks);
}
2024-04-06 20:32:54 +02:00
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StartingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
2024-04-13 12:33:08 +02:00
}