using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Logging;
using SilkroadBot.Domain.Interfaces;
namespace SilkroadBot.Core.Networking;
///
/// Manages TCP connections to Silkroad servers.
/// Handles raw byte I/O, packet framing, and reconnection logic.
///
public class NetworkClient : IDisposable
{
private TcpClient? _tcpClient;
private NetworkStream? _stream;
private CancellationTokenSource? _cts;
private readonly IProtocolAdapter _adapter;
private readonly ILogger _logger;
private readonly byte[] _receiveBuffer = new byte[65536];
private readonly MemoryStream _accumulator = new();
public event Func? PacketReceived;
public event Func? Disconnected;
public bool IsConnected => _tcpClient?.Connected ?? false;
public IPEndPoint? RemoteEndPoint => _tcpClient?.Client?.RemoteEndPoint as IPEndPoint;
public NetworkClient(IProtocolAdapter adapter, ILogger logger)
{
_adapter = adapter;
_logger = logger;
}
///
/// Connect to a server asynchronously.
///
public async Task ConnectAsync(string host, int port, CancellationToken ct = default)
{
_tcpClient = new TcpClient();
_tcpClient.NoDelay = true;
_tcpClient.ReceiveBufferSize = 65536;
_tcpClient.SendBufferSize = 65536;
_logger.LogInformation("Connecting to {Host}:{Port}...", host, port);
await _tcpClient.ConnectAsync(host, port, ct);
_stream = _tcpClient.GetStream();
_logger.LogInformation("Connected to {Host}:{Port}", host, port);
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_ = Task.Run(() => ReceiveLoopAsync(_cts.Token), _cts.Token);
}
///
/// Send a packet to the server.
///
public async Task SendAsync(Packet packet, CancellationToken ct = default)
{
if (_stream == null || !IsConnected)
throw new InvalidOperationException("Not connected");
var encoded = _adapter.EncodePacket(packet.Opcode, packet.Payload, packet.IsEncrypted);
_logger.LogDebug("Sending: {Packet}", packet);
await _stream.WriteAsync(encoded, ct);
}
///
/// Send raw bytes (for handshake/security).
///
public async Task SendRawAsync(byte[] data, CancellationToken ct = default)
{
if (_stream == null || !IsConnected)
throw new InvalidOperationException("Not connected");
await _stream.WriteAsync(data, ct);
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested && IsConnected)
{
int bytesRead = await _stream!.ReadAsync(_receiveBuffer, ct);
if (bytesRead == 0)
{
_logger.LogWarning("Connection closed by remote host");
break;
}
_accumulator.Write(_receiveBuffer, 0, bytesRead);
await ProcessBufferAsync();
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex, "Error in receive loop");
Disconnected?.Invoke(ex);
}
finally
{
Disconnected?.Invoke(null);
}
}
private async Task ProcessBufferAsync()
{
var buffer = _accumulator.ToArray();
int offset = 0;
while (offset < buffer.Length)
{
var result = _adapter.DecodePacket(buffer.AsSpan(offset));
if (!result.Success) break;
var packet = Packet.FromServer(result.Opcode, result.Payload);
_logger.LogDebug("Received: {Packet}", packet);
if (PacketReceived != null)
await PacketReceived.Invoke(packet);
offset += result.BytesConsumed;
}
// Keep unprocessed bytes
_accumulator.SetLength(0);
if (offset < buffer.Length)
_accumulator.Write(buffer, offset, buffer.Length - offset);
}
///
/// Disconnect from the server.
///
public async Task DisconnectAsync()
{
_cts?.Cancel();
_stream?.Close();
_tcpClient?.Close();
_logger.LogInformation("Disconnected");
await Task.CompletedTask;
}
public void Dispose()
{
_cts?.Cancel();
_cts?.Dispose();
_stream?.Dispose();
_tcpClient?.Dispose();
_accumulator.Dispose();
}
}