using System; using System.Diagnostics; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Domain; using Domain.Dto; using MessagePack; namespace Client; public class HttpClientWrapper : IClient { private readonly HttpClient _httpClient; private readonly string _baseUrl; private CancellationTokenSource _cts = new CancellationTokenSource(); private Task? _runningTask; private Func>? _responseConverter; public HttpClientWrapper(Func> responseConverter, string baseUrl = "http://localhost:5555/") { _httpClient = new HttpClient(); _baseUrl = baseUrl; _responseConverter = responseConverter; } public void Start() { _cts = new CancellationTokenSource(); _runningTask = Task.Run(() => RunAsync(_cts.Token)); } public void Stop() { _cts.Cancel(); _runningTask?.Wait(); _httpClient.Dispose(); } private async Task RunAsync(CancellationToken token) { long index = 0; var sw = Stopwatch.StartNew(); var lastMs = 0L; var lastIndex = 0L; var ms = 1000; while (!token.IsCancellationRequested) { try { var url = $"{_baseUrl}fetchpackage?index={index}"; var response = await _httpClient.GetAsync(url, token); if (response.IsSuccessStatusCode) { if (_responseConverter != null) { var data = await _responseConverter(response); if (data != null) { var diff = sw.ElapsedMilliseconds - lastMs; if (diff >= ms) { var fetched = index - lastIndex; System.Console.WriteLine($"Fetched {fetched} data packages in {diff} ms."); lastIndex = index; lastMs = sw.ElapsedMilliseconds; } //System.Console.WriteLine(data); } } else { Console.WriteLine("Response converter not set."); } } else { Console.WriteLine($"Failed to fetch data for index {index}: {response.StatusCode}"); } index++; //await Task.Delay(100, token); // Wait 1 second between requests } catch (TaskCanceledException) { break; } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); await Task.Delay(1000, token); } } } }