File size: 4,749 Bytes
71ce114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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();
    }
}