using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Net;
|
using System.Net.Sockets;
|
using System.Threading;
|
using System.Threading.Tasks;
|
|
namespace WIDESEAWCS_Tasks.SocketServer
|
{
|
public partial class TcpSocketServer
|
{
|
public Task StartAsync(CancellationToken cancellationToken)
|
{
|
if (IsRunning || !_options.Enabled)
|
{
|
return Task.CompletedTask;
|
}
|
|
IPAddress ipAddress = IPAddress.Any;
|
if (IPAddress.TryParse(_options.IpAddress, out IPAddress? parsedAddress))
|
{
|
ipAddress = parsedAddress;
|
}
|
|
_listener = new TcpListener(ipAddress, _options.Port);
|
_listener.Start(_options.Backlog);
|
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
IsRunning = true;
|
|
_ = AcceptLoopAsync(_cts.Token);
|
_monitorTask = Task.Run(() => MonitorClientsAsync(_cts.Token));
|
|
return Task.CompletedTask;
|
}
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
{
|
if (!IsRunning)
|
{
|
return;
|
}
|
|
_cts?.Cancel();
|
_listener?.Stop();
|
|
Task[] tasks;
|
lock (_syncRoot)
|
{
|
tasks = _clientTasks.ToArray();
|
}
|
|
if (tasks.Length > 0)
|
{
|
await Task.WhenAll(tasks);
|
}
|
|
IsRunning = false;
|
}
|
|
private async Task AcceptLoopAsync(CancellationToken cancellationToken)
|
{
|
while (!cancellationToken.IsCancellationRequested)
|
{
|
TcpClient? client = null;
|
try
|
{
|
client = await _listener!.AcceptTcpClientAsync().WaitAsync(cancellationToken);
|
}
|
catch (OperationCanceledException)
|
{
|
break;
|
}
|
catch (ObjectDisposedException)
|
{
|
break;
|
}
|
catch
|
{
|
if (cancellationToken.IsCancellationRequested)
|
{
|
break;
|
}
|
}
|
|
if (client == null)
|
{
|
continue;
|
}
|
|
string clientId = GetClientId(client);
|
lock (_syncRoot)
|
{
|
_clients[clientId] = client;
|
_clientLocks[clientId] = new SemaphoreSlim(1, 1);
|
}
|
}
|
}
|
|
private void RemoveClient(string clientId)
|
{
|
lock (_syncRoot)
|
{
|
if (_clients.TryGetValue(clientId, out var client))
|
{
|
try { client.Close(); } catch { }
|
_clients.Remove(clientId);
|
}
|
|
if (_clientLocks.TryGetValue(clientId, out var sem))
|
{
|
_clientLocks.Remove(clientId);
|
sem.Dispose();
|
}
|
|
_clientLastActive.Remove(clientId);
|
_clientEncodings.Remove(clientId);
|
|
var deviceIds = _deviceBindings.Where(kv => kv.Value == clientId).Select(kv => kv.Key).ToList();
|
foreach (var deviceId in deviceIds)
|
{
|
_deviceBindings.Remove(deviceId);
|
}
|
}
|
}
|
|
private async Task MonitorClientsAsync(CancellationToken cancellationToken)
|
{
|
while (!cancellationToken.IsCancellationRequested)
|
{
|
try
|
{
|
List<string> toRemove = new();
|
lock (_syncRoot)
|
{
|
foreach (var kv in _clientLastActive)
|
{
|
if (_options.IdleTimeoutSeconds > 0 && DateTime.Now - kv.Value > TimeSpan.FromSeconds(_options.IdleTimeoutSeconds))
|
{
|
toRemove.Add(kv.Key);
|
}
|
}
|
}
|
|
foreach (var cid in toRemove)
|
{
|
RemoveClient(cid);
|
Log($"[{DateTime.Now}] TcpSocketServer disconnect idle client {cid}");
|
}
|
}
|
catch
|
{
|
}
|
|
try { await Task.Delay(1000, cancellationToken); } catch { }
|
}
|
}
|
|
public static string GetClientId(TcpClient client)
|
{
|
return client.Client.RemoteEndPoint?.ToString() ?? Guid.NewGuid().ToString();
|
}
|
}
|
}
|