Download src/SilkroadBot.Core/Networking/NetworkClient.cs from Ahmedramadan24/SilkroadBot: direct link, hf CLI and curl.
- Browser
- Download file 4.75 kB
-
https://huggingface.co/Ahmedramadan24/SilkroadBot/resolve/main/src/SilkroadBot.Core/Networking/NetworkClient.cs
- Command line
-
hf download hf://Ahmedramadan24/SilkroadBot/src/SilkroadBot.Core/Networking/NetworkClient.cs
-
curl -L -o NetworkClient.cs https://huggingface.co/Ahmedramadan24/SilkroadBot/resolve/main/src/SilkroadBot.Core/Networking/NetworkClient.cs
4.75 kB
| using System.Net; | |
| using System.Net.Sockets; | |
| using Microsoft.Extensions.Logging; | |
| using SilkroadBot.Domain.Interfaces; | |
| namespace SilkroadBot.Core.Networking; | |
| /// <summary> | |
| /// Manages TCP connections to Silkroad servers. | |
| /// Handles raw byte I/O, packet framing, and reconnection logic. | |
| /// </summary> | |
| public class NetworkClient : IDisposable | |
| { | |
| private TcpClient? _tcpClient; | |
| private NetworkStream? _stream; | |
| private CancellationTokenSource? _cts; | |
| private readonly IProtocolAdapter _adapter; | |
| private readonly ILogger<NetworkClient> _logger; | |
| private readonly byte[] _receiveBuffer = new byte[65536]; | |
| private readonly MemoryStream _accumulator = new(); | |
| public event Func<Packet, Task>? PacketReceived; | |
| public event Func<Exception?, Task>? Disconnected; | |
| public bool IsConnected => _tcpClient?.Connected ?? false; | |
| public IPEndPoint? RemoteEndPoint => _tcpClient?.Client?.RemoteEndPoint as IPEndPoint; | |
| public NetworkClient(IProtocolAdapter adapter, ILogger<NetworkClient> logger) | |
| { | |
| _adapter = adapter; | |
| _logger = logger; | |
| } | |
| /// <summary> | |
| /// Connect to a server asynchronously. | |
| /// </summary> | |
| 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); | |
| } | |
| /// <summary> | |
| /// Send a packet to the server. | |
| /// </summary> | |
| 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); | |
| } | |
| /// <summary> | |
| /// Send raw bytes (for handshake/security). | |
| /// </summary> | |
| 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); | |
| } | |
| /// <summary> | |
| /// Disconnect from the server. | |
| /// </summary> | |
| 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(); | |
| } | |
| } | |