This commit is contained in:
EonaCat authored and Jeroen Saey committed 2026-11-04 07:53:40 +01:00
1 parent 2c5b69bf2c
commit 22dee59f47
132 files changed
+19653 -7192

No files matched your search

@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.Json" Version="2.2.3" />
<PackageReference Include="EonaCat.Json" Version="2.2.5" />
</ItemGroup>
<ItemGroup>
-72
View File
@@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EonaCat.Connections.Client
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
// Root myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse);
public class Contact
{
public string email { get; set; }
public string phone { get; set; }
}
public class Department
{
public string id { get; set; }
public string name { get; set; }
public Manager manager { get; set; }
}
public class Details
{
public int hoursSpent { get; set; }
public List<string> technologiesUsed { get; set; }
public string completionDate { get; set; }
public string expectedCompletion { get; set; }
}
public class Employee
{
public string id { get; set; }
public string name { get; set; }
public string position { get; set; }
public Department department { get; set; }
public List<Project> projects { get; set; }
}
public class Manager
{
public string id { get; set; }
public string name { get; set; }
public Contact contact { get; set; }
}
public class Project
{
public string projectId { get; set; }
public string projectName { get; set; }
public string startDate { get; set; }
public List<Task> tasks { get; set; }
}
public class Root
{
public Employee employee { get; set; }
}
public class Task
{
public string taskId { get; set; }
public string title { get; set; }
public string status { get; set; }
public Details details { get; set; }
}
}
+549 -127
View File
@@ -1,205 +1,570 @@
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Reflection;
using System.Text;
namespace EonaCat.Connections.Client.Example
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
public class Program
{
private const bool UseProcessor = true;
private static JsonDataProcessor<dynamic> processor = new JsonDataProcessor<dynamic>();
private const bool IsHeartBeatEnabled = false;
private static int SEND_DELAY_IN_MILLISECONDS = 1000 * 40;
private static List<NetworkClient> _clients = new List<NetworkClient>();
private static long clientCount = 1;
private static long clientsConnected = 0;
private static string _jsonContent;
//public static string SERVER_IP = "10.40.11.22";
public static string SERVER_IP = "127.0.0.1";
private static Dictionary<NetworkClient, JsonDataProcessor<List<Root>>> _clientsProcessors = new Dictionary<NetworkClient, JsonDataProcessor<List<Root>>>();
private static bool testDataProcessor;
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; } = true;
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 System.Threading.Tasks.Task Main(string[] args)
public static async Task Main(string[] args)
{
for (long i = 0; i < clientCount; i++)
_configuration = new Configuration
{
var clientName = $"User {i}";
var client = await CreateClientAsync().ConfigureAwait(false);
_clients.Add(client);
Protocol = ProtocolType.TCP,
Host = SERVER_IP,
Port = 1111,
if (testDataProcessor)
{
_clientsProcessors[client] = new JsonDataProcessor<List<Root>>();
}
else
{
_ = StartClientAsync(clientName, client);
}
}
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",
while (true)
EnableConnectionDebugLogs = true,
};
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
string message = string.Empty;
Console.WriteLine("[TCP Client] Application terminating, forcing cleanup...");
CleanupAllClients();
};
if (WaitForMessage)
try
{
if (!EnableLoadTest && !EnableStressTest)
{
Console.Write("Enter message to send (or 'exit' to quit): ");
message = Console.ReadLine();
for (long i = 0; i < clientCount; i++)
{
var clientName = $"User {i}";
var client = await CreateClientAsync().ConfigureAwait(false);
_clients.Add(client);
_ = StartClientAsync(clientName, client);
}
}
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
processor.OnProcessMessage += Processor_OnProcessMessage;
processor.OnProcessTextMessage += Processor_OnProcessTextMessage;
processor.OnError += Processor_OnError;
processor.OnClientRemovedDueToIdle += Processor_OnClientRemovedDueToIdle;
if (!IgnoreAutoDelay)
{
foreach (var client in _clients)
{
await client.DisconnectAsync().ConfigureAwait(false);
}
break;
SetDelay();
}
var jsonUrl = "https://sample.json-format.com/api/download?url=https%3A%2F%2Ffiles.jsons.live%2Femployees%2F5-level%2F20-MB%2Fformatted.json&name=20%20MB%205%20Level%20Formatted.json";
try
bool shouldExit = false;
while (!shouldExit)
{
if (string.IsNullOrEmpty(_jsonContent) && UseJson)
{
using var httpClient = new HttpClient();
_jsonContent = await httpClient.GetStringAsync(jsonUrl);
string message = string.Empty;
var jsonSize = Encoding.UTF8.GetByteCount(_jsonContent);
WriteToLog($"Using large JSON file (size: {jsonSize / 1024 / 1024} MB)");
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 (UseJson)
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
message = _jsonContent;
shouldExit = true;
break;
}
if (UseJsonProcessorTest)
if (!string.IsNullOrEmpty(message) && message.Equals("connect", StringComparison.OrdinalIgnoreCase))
{
foreach (var client in _clients)
{
var processor = _clientsProcessors[client];
processor.OnProcessTextMessage += (sender, e) =>
{
WriteToLog($"Processed message from {e.ClientName}: {e.Text}");
};
processor.OnProcessMessage += (sender, e) =>
{
WriteToLog($"Processed JSON message from {e.ClientName} ({e.ClientEndpoint}): {e.Data}");
};
processor.MaxAllowedBufferSize = 50 * 1024 * 1024; // 10 MB
var json = _jsonContent;
await client.ConnectAsync().ConfigureAwait(false);
}
continue;
}
while (true)
{
json = "TEST1" + _jsonContent + "TEST2";
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 System.Threading.Tasks.Task.Delay(100).ConfigureAwait(false);
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)
catch (Exception exception)
{
if (TESTBYTES)
WriteToLog($"Failed to download large JSON file: {exception.Message}");
}
if (!string.IsNullOrEmpty(message))
{
foreach (var client in _clients)
{
var bytes = new byte[] { 0x00, 0x04, 0x31, 0x32, 0x30, 0x30 };
await client.SendAsync(bytes).ConfigureAwait(false);
}
else
{
await client.SendAsync(message).ConfigureAwait(false);
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 System.Threading.Tasks.Task.Delay(1000).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 async System.Threading.Tasks.Task StartClientAsync(string clientName, NetworkClient client)
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<dynamic> 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);
// Send nickname
await client.SendNicknameAsync(clientName);
// Send a message
await client.SendAsync($"Hello server, my name is {clientName}!");
}
private static async Task<NetworkClient> CreateClientAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Host = SERVER_IP,
Port = 1111,
UseAesEncryption = false,
EnableHeartbeat = IsHeartBeatEnabled,
AesPassword = "EonaCat.Connections.Password",
//Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss"),
};
var client = new NetworkClient(_configuration);
var client = new NetworkClient(config);
// Subscribe to events
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}";
};
}; ;
if (UseProcessor)
client.OnDataReceived += async (sender, e) =>
{
_clientsProcessors[client] = new JsonDataProcessor<List<Root>>();
_clientsProcessors[client].OnError += (sender, e) =>
var data = e.Data;
if (Encoding.UTF8.GetString(data).Contains("Server broadcast"))
{
Console.WriteLine($"Processor error: {e.Message}");
};
var broadcastData = Encoding.UTF8.GetString(data).Split(new[] { "Server broadcast: " }, StringSplitOptions.None).LastOrDefault()?.Trim();
Console.Title = broadcastData;
return;
}
_clientsProcessors[client].OnProcessTextMessage += (sender, e) =>
Console.WriteLine($"Received: {data.Length} bytes");
if (UseJsonProcessorTest)
{
Console.WriteLine($"Processed text message from {e.ClientName}: {e.Text}");
};
_clientsProcessors[client].OnProcessMessage += (sender, e) =>
{
ProcessMessage(e.Data, e.ClientName, e.ClientEndpoint ?? "Unknown endpoint");
};
}
client.OnDataReceived += (sender, e) =>
{
if (UseProcessor)
{
_clientsProcessors[client].Process(e.StringData, currentClientName: e.Nickname);
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}");
@@ -235,9 +600,6 @@ namespace EonaCat.Connections.Client.Example
message = $"Disconnected from server (remote close). Reason: {e.Reason}";
}
}
WriteToLog(message);
Console.WriteLine(message);
Console.Title = $"Total clients {--clientsConnected}";
};
@@ -249,7 +611,15 @@ namespace EonaCat.Connections.Client.Example
private static void ProcessMessage(object message, string clientName, string remoteEndpoint)
{
WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}");
if (ShowInConsole)
{
WriteToLog($"Processed message from {clientName} ({remoteEndpoint}): {message}");
}
else
{
WriteToLog($"Processed message from {clientName} ({remoteEndpoint})");
}
if (PressEnterForNextMessage)
{
Console.ReadKey();
@@ -263,12 +633,64 @@ namespace EonaCat.Connections.Client.Example
private static void Client_OnGeneralError(object? sender, EventArguments.ErrorEventArgs e)
{
WriteToLog($"General error: {e.Message} => {e.Exception?.Message} => {e.Nickname}");
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}");
WriteToLog($"Encryption error: {e.Message} {e.Exception?.Message} {e.Nickname}");
}
/// <summary>
/// Run a stress test with multiple clients and many messages
/// </summary>
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)
@@ -307,4 +729,4 @@ namespace EonaCat.Connections.Client.Example
}
}
}
}
}