using EonaCat.Connections.Helpers; using EonaCat.Connections.Models; using System.Reflection; using System.Text; namespace EonaCat.Connections.Client.Example { public class Program { private static JsonDataProcessor processor = new JsonDataProcessor(); private const bool IsHeartBeatEnabled = false; private static int SEND_DELAY_IN_MILLISECONDS = 1000 * 40; private static List _clients = new List(); private static long clientCount = 1; private static long clientsConnected = 0; private static string _jsonContent; public static string SERVER_IP = "127.0.0.1"; static int i = 0; private static Configuration _configuration; public static bool WaitForMessage { get; private set; } public static bool PressEnterForNextMessage { get; private set; } public static bool ToConsoleOnly { get; private set; } public static bool UseJson { get; private set; } = true; public static bool TESTBYTES { get; private set; } public static bool UseJsonProcessorTest { get; private set; } = true; public static bool ShowInConsole { get; private set; } public static bool UseJsonProcessorInternalTest { get; private set; } = true; public static bool UseTestJsonFive { get; private set; } = true; public static bool UseTestJsonTen { get; private set; } public static bool UseTestJsonTwenty { get; private set; } public static bool UseTestJsonThirty { get; private set; } public static bool UseTestJsonOneHundred { get; private set; } public static bool IgnoreAutoDelay { get; private set; } public static bool IsConnected { get; private set; } public static bool CheckJsonPayloadMessage { get; set; } public static bool EnableStressTest { get; private set; } = false; public static bool EnableLoadTest { get; private set; } = false; public static async Task Main(string[] args) { _configuration = new Configuration { Protocol = ProtocolType.TCP, Host = SERVER_IP, Port = 1111, Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null), UseAesEncryption = false, EnableHeartbeat = IsHeartBeatEnabled, AesPassword = "itudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tincidunt sollicitudin posuere. Phasellus tincidunt sollicitudin posuere. Nam tristique feugiat est vitae mollis.\",\"version\": 8.39},{\"name\": \"Bhupesh Menon\",\"language\": \"Hindi\",\"id\": \"0CEPNRDV98KT3ORP\",\"bio\": \"Maecenas tempus neque ut porttitor malesuada. Phasellus massa ligula, hendrerit eget efficitur eget, tincidunt in ligula. Quisque mauris ligula, efficitur porttitor sodales ac, lacinia non ex. Maecenas quis nisi nunc.\",\"version\": 2.69},{\"name\": \"Rohini Vasav\",\"language\": \"Hindi\",\"id\": \"UEFML43TCGS04KWM\",\"bio\": \"Ut accumsan, est vel fringilla varius, purus augue blandit nisl, eu rhoncus ligula purus vel dolor. Ut maximus, libero nec facilisis fringilla, ex sem sollicitudin leo, non congue tortor ligula in eros. Nam rutrum sollicitudin ante tempus consequat. Aliquam scelerisque pretium tellus, sed accumsan est ultrices id. Suspendisse sit amet ullamcorper sem.\",\"version\": 9.3},{\"name\": \"Sunil Kapoor\",\"language\": \"Hindi\",\"id\": \"VY2A0APGVHK5NAW2\",\"bio\": \"Proin tempus eu risus nec mattis. Ut dictum, ligula eget sagittis maximus, tellus mi varius ex, a accumsan justo tellus vitae leo. In id elit malesuada, pulvinar mi eu, imperdiet nulla.\",\"version\": 8.04},{\"name\": \"Zamokuhle Zulu\",\"language\": \"isiZulu\",\"id\": \"XU7BX2F8M5PVZ1EF\",\"bio\": \"Etiam congue dignissim volutpat. Phasellus tinc", EnableConnectionDebugLogs = true, }; AppDomain.CurrentDomain.ProcessExit += (sender, e) => { Console.WriteLine("[TCP Client] Application terminating, forcing cleanup..."); CleanupAllClients(); }; try { if (!EnableLoadTest && !EnableStressTest) { for (long i = 0; i < clientCount; i++) { var clientName = $"User {i}"; var client = await CreateClientAsync().ConfigureAwait(false); _clients.Add(client); _ = StartClientAsync(clientName, client); } } processor.OnProcessMessage += Processor_OnProcessMessage; processor.OnProcessTextMessage += Processor_OnProcessTextMessage; processor.OnError += Processor_OnError; processor.OnClientRemovedDueToIdle += Processor_OnClientRemovedDueToIdle; if (!IgnoreAutoDelay) { SetDelay(); } bool shouldExit = false; while (!shouldExit) { string message = string.Empty; if (WaitForMessage) { Console.Write("Enter message to send (or 'exit' to quit): "); message = Console.ReadLine(); foreach (var client in _clients) { await client.DisconnectAsync().ConfigureAwait(false); } Console.WriteLine("Disconnected all clients. Press any key to continue..."); Console.ReadKey(); Console.ReadLine(); foreach (var client in _clients) { await client.ConnectAsync().ConfigureAwait(false); } Console.WriteLine("Reconnected all clients"); } if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase)) { shouldExit = true; break; } if (!string.IsNullOrEmpty(message) && message.Equals("connect", StringComparison.OrdinalIgnoreCase)) { foreach (var client in _clients) { await client.ConnectAsync().ConfigureAwait(false); } continue; } if (EnableStressTest) { await RunStressTestAsync(); return; } if (EnableLoadTest) { await RunLoadTestAsync(10_000, 10, 1000, 10_000); return; } var jsonUrl = "https://samples.json-format.com/employees/json/employees_500KB.json"; try { if (string.IsNullOrEmpty(_jsonContent) && UseJson) { using var httpClient = new HttpClient(); _jsonContent = await httpClient.GetStringAsync(jsonUrl); } if (UseJson) { message = _jsonContent; } if (UseTestJsonTwenty) { message = File.ReadAllText("Z:\\json\\20mb.json"); } if (UseTestJsonThirty) { message = File.ReadAllText("Z:\\json\\30mb.json"); } if (UseTestJsonFive) { message = File.ReadAllText("Z:\\json\\5mb.json"); } if (UseTestJsonTen) { message = File.ReadAllText("Z:\\json\\10mb.json"); } if (UseTestJsonOneHundred) { message = File.ReadAllText("Z:\\json\\100mb.json"); } var jsonSize = Encoding.UTF8.GetByteCount(message); WriteToLog($"Using file (size: {jsonSize / 1024 / 1024} MB)"); if (UseJsonProcessorInternalTest) { foreach (var client in _clients) { var json = message; processor.Process(json, "TestClient"); await Task.Delay(100).ConfigureAwait(false); } } } catch (Exception exception) { WriteToLog($"Failed to download large JSON file: {exception.Message}"); } if (!string.IsNullOrEmpty(message)) { foreach (var client in _clients) { if (TESTBYTES) { var bytes = new byte[] { 0x00, 0x04, 0x31, 0x32, 0x30, 0x30 }; await client.SendAsync(bytes).ConfigureAwait(false); } else { await client.SendAsync(message).ConfigureAwait(false); } } } await Task.Delay(SEND_DELAY_IN_MILLISECONDS).ConfigureAwait(false); } } catch (Exception ex) { Console.WriteLine($"[TCP Client] Fatal error: {ex.Message}"); Console.WriteLine(ex.StackTrace); } finally { Console.WriteLine("[TCP Client] Stopping all clients..."); CleanupAllClients(); Console.WriteLine("[TCP Client] Stopped."); } } private static void CleanupAllClients() { foreach (var client in _clients) { try { client?.Dispose(); } catch (Exception ex) { Console.WriteLine($"Error disposing client: {ex.Message}"); } } _clients.Clear(); } static long totalKeepAlives = 0; private static async Task KeepAliveBroadCastTest() { var client = _clients.FirstOrDefault(); client.OnDataReceived += (sender, e) => { if (e.StringData.Contains("KeepAlive Test")) { Console.Title = $"Received KeepAlive Test response at {DateTime.Now} (total {++totalKeepAlives})"; Console.WriteLine($"Received KeepAlive Test response: {e.StringData}"); } else { Console.WriteLine($"Received data: {e.StringData}"); } }; await client.SendAndWaitForResponseAsync("KeepAliveTest", TimeSpan.FromSeconds(30)).ContinueWith(task => { if (task.IsCompletedSuccessfully) { var response = task.Result; Console.WriteLine($"Received response for KeepAliveTest: {response}"); } else { Console.WriteLine($"KeepAliveTest failed: {task.Exception?.Message}"); } }); } private static async Task TimerTest() { System.Timers.Timer timer = new System.Timers.Timer(1000); timer.Elapsed += (sender, e) => { Console.WriteLine("IK BEN GEFIRED!"); }; timer.Start(); while (true) { timer.Start(); Console.WriteLine("JIJ BENT EEN NERD !"); await Task.Delay(950); timer.Stop(); Console.WriteLine("JIJ BENT EEN NERD ! (NA TIMER)"); await Task.Delay(1000).ConfigureAwait(false); } } private static void DelayTest() { while (true) { _clients.FirstOrDefault().SendAsync($"Hello server, this is a delayed message at {DateTime.Now}").ConfigureAwait(false); Console.WriteLine($"{DateTime.Now} : Sent delayed message"); Thread.Sleep(30_000); } } private static async Task DisconnectTest() { while (true) { var client = new NetworkClient(new Configuration() { Host = "127.0.0.1", Port = 1111, Certificate = CertificateHelper.GetCertificate(certificateThumbprint: "4e34475f8618f4cbd65a9852b8bf45e740a52fff"), }); client.OnDataReceived += Client_OnDataReceived1; while (true) { await Task.Delay(10000).ConfigureAwait(false); await client.ConnectAsync().ConfigureAwait(false); await Task.Delay(1000).ConfigureAwait(false); await client.DisconnectAsync().ConfigureAwait(false); await Task.Delay(1000).ConfigureAwait(false); await client.ConnectAsync().ConfigureAwait(false); await Task.Delay(1000).ConfigureAwait(false); await client.DisconnectAsync().ConfigureAwait(false); await Task.Delay(1000).ConfigureAwait(false); await client.ConnectAsync().ConfigureAwait(false); await client.SendAsync("Hallo ik ben een brasser zie je dat niet;"); } } } private static async void Client_OnDataReceived1(object? sender, DataReceivedEventArgs e) { var client = (NetworkClient)sender; if (client == null) { return; } Console.WriteLine($"Received data from server: {e.StringData}"); await client.SendAsync($"Echo: {e.StringData}").ConfigureAwait(false); await client.DisconnectAsync().ConfigureAwait(false); await client.ConnectAsync(); } private static async Task RikAsync() { var client = new NetworkClient(new Configuration() { Host = "127.0.0.1", Port = 1111, Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null), EnableConnectionDebugLogs = true, MessageFraming = FramingMode.LengthPrefixed, }); client.OnConnected += Client_OnConnected; client.OnDisconnected += Client_OnDisconnected; client.OnDataReceived += Client_OnDataReceived; client.OnGeneralError += Client_OnGeneralError; client.OnEncryptionError += Client_OnEncryptionError; client.OnSslError += Client_OnSslError; await client.ConnectAsync().ConfigureAwait(false); while (true) { await client.ConnectAsync(); await Task.Delay(250); } } private static void Client_OnDataReceived(object? sender, DataReceivedEventArgs e) { if (e.Data != null) { var dataSize = e.Data.Length; if (CheckJsonPayloadMessage) { Console.WriteLine($"Received JSON from server (size: {dataSize} bytes)"); } else { Console.WriteLine($"Received data from server (size: {dataSize} bytes) {e.StringData}"); } } else { Console.WriteLine("Received data from server (no data)"); } } private static void Client_OnDisconnected(object? sender, EventArguments.ConnectionEventArgs e) { Console.WriteLine($"Disconnected from server at {e.RemoteEndPoint}"); IsConnected = false; } private static void Client_OnConnected(object? sender, EventArguments.ConnectionEventArgs e) { Console.WriteLine($"Connected to server at {e.RemoteEndPoint}"); IsConnected = true; SendMessagesContinuously(sender); } private static void SendMessagesContinuously(object? sender) { while (IsConnected) { var message = $"Hello server, this is message {++i}"; ((NetworkClient)sender).SendAsync(message).ConfigureAwait(false); Console.WriteLine($"{DateTime.Now} : Sent message: {message}"); Thread.Sleep(1); } } private static void Processor_OnClientRemovedDueToIdle(object? sender, string e) { Console.WriteLine($"Client removed due to idle: {e}"); } private static void Processor_OnError(object? sender, Exception e) { Console.WriteLine("Error: " + e.Message); } private static void Processor_OnProcessTextMessage(object? sender, ProcessedTextMessage e) { if (ShowInConsole) { Console.WriteLine("Received text: " + e.Text); } else { Console.WriteLine("Received text OK"); } } private static void Processor_OnProcessMessage(object? sender, ProcessedMessage e) { if (ShowInConsole) { Console.WriteLine("Received JSON message OK: " + e.Data); } else { Console.WriteLine("Received JSON message OK"); } } private static void SetDelay() { if (UseTestJsonOneHundred) { SEND_DELAY_IN_MILLISECONDS = 1000 * 120; } else if (UseTestJsonThirty) { SEND_DELAY_IN_MILLISECONDS = 1000 * 60; } else if (UseTestJsonTwenty) { SEND_DELAY_IN_MILLISECONDS = 1000 * 40; } else if (UseTestJsonTen) { SEND_DELAY_IN_MILLISECONDS = 1000 * 20; } } private static void SmallMessagesTest() { while (true) { for (int i = 0; i < 1000; i++) { var message = $"{i}"; _clients.ForEach(async client => { await client.SendAsync(message).ConfigureAwait(false); }); } Thread.Sleep(10); } } private static async Task DanielTestAsync() { Console.WriteLine("SocketTest Client started."); EonaCat.Connections.NetworkClient _networkClient = new EonaCat.Connections.NetworkClient(new Configuration() { Host = "127.0.0.1", Port = 1111, }); Console.WriteLine("Connecting to server..."); _ = _networkClient.ConnectAsync(); await Task.Delay(1000); Console.WriteLine("Disconnecting from server..."); _ = _networkClient.DisconnectAsync(); _ = _networkClient.DisposeAsync(); await _networkClient.ConnectAsync(); _networkClient.Dispose(); _networkClient = null; while (true) { await Task.Delay(1000); Console.WriteLine("Keeping the process alive..."); } Console.WriteLine("DanielTest finished..."); Console.ReadKey(); } private static async Task StartClientAsync(string clientName, NetworkClient client) { await client.ConnectAsync().ConfigureAwait(false); await client.SendAsync($"Hello server, my name is {clientName}!"); } private static async Task CreateClientAsync() { var client = new NetworkClient(_configuration); client.OnConnected += (sender, e) => { client.SendNicknameAsync("MYTESTNICKNAME"); WriteToLog($"Connected to server at {e.RemoteEndPoint}"); Console.WriteLine($"Connected to server at {e.RemoteEndPoint}"); Console.Title = $"Total clients {++clientsConnected}"; }; ; client.OnDataReceived += async (sender, e) => { var data = e.Data; if (Encoding.UTF8.GetString(data).Contains("Server broadcast")) { var broadcastData = Encoding.UTF8.GetString(data).Split(new[] { "Server broadcast: " }, StringSplitOptions.None).LastOrDefault()?.Trim(); Console.Title = broadcastData; return; } Console.WriteLine($"Received: {data.Length} bytes"); if (UseJsonProcessorTest) { processor.Process(e, currentClientName: e.Nickname, e.RemoteEndPoint.ToString()); return; } else { Console.WriteLine(e.StringData); return; WriteToLog($"Server says: {(e.IsBinary ? $"{e.Data.Length} bytes" : "We got a json message")}"); Console.WriteLine($"{e.StringData}"); if (PressEnterForNextMessage) { Console.ReadKey(); } } }; client.OnDisconnected += (sender, e) => { var message = string.Empty; if (e.Reason == DisconnectReason.LocalClosed) { if (e.Exception != null) { message = $"Disconnected from server (local close). Exception: {e.Exception.Message}"; } else { message = "Disconnected from server (local close)."; } } else { if (e.Exception != null) { message = $"Disconnected from server (remote close). Reason: {e.Reason}. Exception: {e.Exception.Message}"; } else { message = $"Disconnected from server (remote close). Reason: {e.Reason}"; } } Console.Title = $"Total clients {--clientsConnected}"; }; client.OnEncryptionError += Client_OnEncryptionError; client.OnGeneralError += Client_OnGeneralError; client.OnSslError += Client_OnSslError; return client; } private static void ProcessMessage(object message, string clientName, string remoteEndpoint) { if (ShowInConsole) { WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}"); } else { WriteToLog($"Processed message from {clientName} ({remoteEndpoint})"); } if (PressEnterForNextMessage) { Console.ReadKey(); } } private static void Client_OnSslError(object? sender, EventArguments.ErrorEventArgs e) { WriteToLog($"SSL error: {e.Message} => {e.Exception?.Message} => {e.Nickname}"); } private static void Client_OnGeneralError(object? sender, EventArguments.ErrorEventArgs e) { WriteToLog($"General error: {e.Message} {e.Exception?.Message} {e.Nickname}"); } private static void Client_OnEncryptionError(object? sender, EventArguments.ErrorEventArgs e) { WriteToLog($"Encryption error: {e.Message} {e.Exception?.Message} {e.Nickname}"); } /// /// Run a stress test with multiple clients and many messages /// public static async Task RunStressTestAsync(int totalClients = 1000, int totalMessages = 100) { try { int clients = totalClients; int messages = totalMessages; // Close existing clients so stress test can use the port CleanupAllClients(); await Task.Delay(1000); // Wait for port to be released var stressTest = new Tests.StressTest(_configuration, clients, messages); await stressTest.RunAsync(); WriteToLog($"Stress test completed. Report:{Environment.NewLine}{stressTest.Result}"); // Recreate clients if needed for (long i = 0; i < clientCount; i++) { var clientName = $"User {i}"; var client = await CreateClientAsync().ConfigureAwait(false); _clients.Add(client); _ = StartClientAsync(clientName, client); } } catch (Exception ex) { Console.WriteLine($"Error running stress test: {ex.Message}"); } finally { Console.WriteLine("Stress test completed."); Console.ReadKey(); } } private static async Task RunLoadTestAsync(int totalConnections, int durationMinutes, int connectionRatePerSecond, int messageRate) { var tester = new LoadTester(_configuration, totalConnections); var task = tester.RunAsync( duration: TimeSpan.FromMinutes(durationMinutes), connectionRatePerSecond: connectionRatePerSecond, // Establish connections/sec messageRate: messageRate // messages/sec/connection ); await task; var report = tester.GetReport(); WriteToLog($"Load test completed. Report:{Environment.NewLine}{report}"); Console.ReadKey(); } public static void WriteToLog(string message) { try { if (ToConsoleOnly) { var dateTimeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); Console.WriteLine($"{dateTimeNow}: {message}"); return; } var logFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".", "client_log.txt"); var logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}{Environment.NewLine}"; if (!File.Exists(logFilePath)) { File.WriteAllText(logFilePath, logMessage); return; } if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024) // 5 MB { var archiveFilePath = Path.Combine(Path.GetDirectoryName(logFilePath) ?? ".", $"client_log_{DateTime.Now:yyyyMMdd_HHmmss}.txt"); File.Move(logFilePath, archiveFilePath); File.WriteAllText(logFilePath, logMessage); return; } File.AppendAllText(logFilePath, logMessage); } catch { // Ignore logging errors } } } }