Supercell.GUT/Supercell.GUT.Server/Network/Tcp/TcpGateway.cs
BreadDEV ad23f95319 [v0.0.1] very early state server
only basic messages, wip.
2024-03-04 20:19:32 +07:00

60 lines
1.7 KiB
C#

using System.Net.Sockets;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Supercell.GUT.Server.Network.Options;
namespace Supercell.GUT.Server.Network.Tcp;
internal class TcpGateway : IServerGateway
{
private const int TcpBacklog = 100;
private readonly ILogger _logger;
private readonly IOptions<GatewayOptions> _options;
private readonly IGatewayEventListener _listener;
private readonly Socket _socket;
private CancellationTokenSource? _listenCancellation;
private Task? _listenTask;
public TcpGateway(IOptions<GatewayOptions> options, ILogger<TcpGateway> logger, IGatewayEventListener listener)
{
_logger = logger;
_options = options;
_listener = listener;
_socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
_socket.Bind(_options.Value.ListenEndPoint);
_socket.Listen(TcpBacklog);
_listenCancellation = new();
_listenTask = RunAsync(_listenCancellation.Token);
_logger.LogInformation("Gateway is listening at {ipEndPoint}", _options.Value.ListenEndPoint);
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Socket? socket = await _socket.AcceptSocketAsync(cancellationToken);
if (socket == null) break;
_listener.OnConnect(new TcpSocketEntity(socket));
}
}
public async Task ShutdownAsync()
{
if (_listenCancellation != null)
{
await _listenCancellation.CancelAsync();
await _listenTask!;
}
_socket.Close();
}
}