Updated
This commit is contained in:
1 parent
2c5b69bf2c
commit
22dee59f47
132 files changed
+19653
-7192
No files matched your search
@@ -1,23 +1,35 @@
|
||||
using EonaCat.Connections.Models;
|
||||
using EonaCat.Connections.Helpers;
|
||||
using EonaCat.Connections.Models;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection;
|
||||
|
||||
namespace EonaCat.Connections.Server.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 IsHeartBeatEnabled = false;
|
||||
private static NetworkServer _server;
|
||||
private static TcpListener _tcpListener;
|
||||
private static readonly object _tcpLock = new object();
|
||||
|
||||
public static bool WaitForMessage { get; private set; } = true;
|
||||
public static bool WaitForMessage { get; private set; }
|
||||
public static bool ToConsoleOnly { get; private set; } = true;
|
||||
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
|
||||
CreateServerAsync().ConfigureAwait(false);
|
||||
|
||||
await BroadCastLoopTest();
|
||||
|
||||
while (true)
|
||||
{
|
||||
await Task.Delay(1000).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
ConnectedClientsTest();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var message = string.Empty;
|
||||
@@ -27,6 +39,10 @@ namespace EonaCat.Connections.Server.Example
|
||||
Console.Write("Enter message to send (or 'exit' to quit): ");
|
||||
message = Console.ReadLine();
|
||||
}
|
||||
else
|
||||
{
|
||||
message = $"Server broadcast at {DateTime.Now:HH:mm:ss}";
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -45,48 +61,145 @@ namespace EonaCat.Connections.Server.Example
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task BroadCastLoopTest()
|
||||
{
|
||||
long keepAliveCounter = 0;
|
||||
while (true)
|
||||
{
|
||||
var message = $"KeepAlive Test {++keepAliveCounter}";
|
||||
if (_server.GetClients().Any(c => c.Value.IsConnected))
|
||||
{
|
||||
Console.WriteLine($"Broadcasting: {message}");
|
||||
await _server.BroadcastAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Task.Delay(1000).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConnectedClientsTest()
|
||||
{
|
||||
foreach (var client in _server.GetClients())
|
||||
{
|
||||
Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}");
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
Console.WriteLine("Press 'c' to check connected clients, 'q' to quit.");
|
||||
var key = Console.ReadKey(true);
|
||||
if (key.KeyChar == 'c')
|
||||
{
|
||||
foreach (var client in _server.GetClients())
|
||||
{
|
||||
Console.WriteLine($"Connected Client: ID={client.Value.Id}, Nickname={client.Value.Nickname}, RemoteEndPoint={client.Value.RemoteEndPoint}, IsConnected={client.Value.IsConnected}");
|
||||
}
|
||||
|
||||
Console.WriteLine("Total clients: " + _server.GetClients().Count);
|
||||
Console.WriteLine("Total connected clients: " + _server.GetClients().Count(c => c.Value.IsConnected));
|
||||
}
|
||||
else if (key.KeyChar == 'q')
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DanielTestServer()
|
||||
{
|
||||
lock (_tcpLock)
|
||||
{
|
||||
try
|
||||
{
|
||||
_tcpListener?.Stop();
|
||||
_tcpListener?.Server?.Close();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_tcpListener = null;
|
||||
}
|
||||
|
||||
lock (_tcpLock)
|
||||
{
|
||||
_tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1111);
|
||||
_tcpListener.Start();
|
||||
Console.WriteLine("Listener started");
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
var client = await _tcpListener.AcceptTcpClientAsync();
|
||||
if (client != null)
|
||||
{
|
||||
Console.WriteLine("DanielTestServer: Client connected.");
|
||||
}
|
||||
|
||||
Console.ReadKey();
|
||||
_tcpListener.Stop();
|
||||
Console.WriteLine("DanielTestServer: Listener stopped.");
|
||||
await DanielTestServer();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CreateServerAsync()
|
||||
{
|
||||
var config = new Configuration
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
Protocol = Models.ProtocolType.TCP,
|
||||
Host = "0.0.0.0",
|
||||
Port = 1111,
|
||||
EnableHealthApi = true,
|
||||
HealthApiBindAddress = System.Net.IPAddress.Loopback,
|
||||
|
||||
Certificate = CertificateHelper.GetCertificate(certificatePath: @"C:\ProgramData\EonaCat\localhost.pfx", certificatePassword: null),
|
||||
UseAesEncryption = false,
|
||||
MaxConnections = 100000,
|
||||
AesPassword = "EonaCat.Connections.Password",
|
||||
//Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss"),
|
||||
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",
|
||||
EnableHeartbeat = IsHeartBeatEnabled,
|
||||
|
||||
EnableConnectionDebugLogs = true,
|
||||
};
|
||||
|
||||
_server = new NetworkServer(config);
|
||||
|
||||
// Subscribe to events
|
||||
_server.OnConnected += (sender, e) =>
|
||||
{
|
||||
WriteToLog($"Client {e.ClientId} connected from {e.RemoteEndPoint}");
|
||||
Console.WriteLine($"New connection from {e.RemoteEndPoint} with Client ID: {e.ClientId}");
|
||||
};
|
||||
|
||||
_server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}");
|
||||
|
||||
_server.OnDataReceived += async (sender, e) =>
|
||||
{
|
||||
WriteToLog($"Received from {e.ClientId} ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}");
|
||||
|
||||
// Echo back the message
|
||||
if (e.IsBinary)
|
||||
{
|
||||
await _server.SendToClientAsync(e.ClientId, e.Data);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _server.SendToClientAsync(e.ClientId, e.StringData);
|
||||
}
|
||||
};
|
||||
|
||||
_server.OnDisconnected += (sender, e) =>
|
||||
{
|
||||
WriteToLog($"Client {e.ClientId} disconnected from {e.RemoteEndPoint}");
|
||||
Console.WriteLine($"Connection terminated from {e.RemoteEndPoint} with Client ID: {e.ClientId}");
|
||||
|
||||
Console.WriteLine($" → Reason: {e.Reason}");
|
||||
Console.WriteLine($" → Initiated By: {e.Initiator}");
|
||||
Console.WriteLine($" → Details: {e.ReasonDetails}");
|
||||
|
||||
if (e.ConnectionDuration.HasValue)
|
||||
{
|
||||
Console.WriteLine($" → Duration: {e.ConnectionDuration.Value.TotalSeconds:F2}s");
|
||||
}
|
||||
|
||||
if (e.HasException)
|
||||
{
|
||||
Console.WriteLine($" → Exception: {e.Exception.GetType().Name}: {e.Exception.Message}");
|
||||
}
|
||||
|
||||
if (e.DiagnosticContext != null && e.DiagnosticContext.Count > 0)
|
||||
{
|
||||
Console.WriteLine($" → Diagnostic Context:");
|
||||
foreach (var kvp in e.DiagnosticContext)
|
||||
{
|
||||
Console.WriteLine($" {kvp.Key}: {kvp.Value}");
|
||||
}
|
||||
}
|
||||
|
||||
var message = string.Empty;
|
||||
if (e.Reason == DisconnectReason.LocalClosed)
|
||||
{
|
||||
@@ -103,17 +216,33 @@ namespace EonaCat.Connections.Server.Example
|
||||
{
|
||||
if (e.Exception != null)
|
||||
{
|
||||
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Exception: {e.Exception.Message}";
|
||||
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}. Exception: {e.Exception.Message}";
|
||||
}
|
||||
else
|
||||
{
|
||||
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}";
|
||||
message = $"{e.Nickname} disconnected from server (remote close). Reason: {e.Reason}. Initiator: {e.Initiator}";
|
||||
}
|
||||
}
|
||||
WriteToLog(message);
|
||||
Console.WriteLine(message);
|
||||
};
|
||||
|
||||
_server.OnConnectedWithNickname += (sender, e) => WriteToLog($"Client {e.ClientId} connected with nickname: {e.Nickname}");
|
||||
|
||||
_server.OnDataReceived += async (sender, e) =>
|
||||
{
|
||||
WriteToLog($"Received from {e.ClientId} ({e.Nickname ?? "NoNickname"}) ({e.RemoteEndPoint.ToString()}): {(e.IsBinary ? $"{e.Data.Length} bytes" : "a message")}");
|
||||
|
||||
if (e.IsBinary)
|
||||
{
|
||||
await _server.SendToClientAsync(e.ClientId, e.Data);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _server.SendToClientAsync(e.ClientId, e.StringData);
|
||||
}
|
||||
};
|
||||
|
||||
_ = _server.StartAsync();
|
||||
}
|
||||
|
||||
@@ -137,7 +266,7 @@ namespace EonaCat.Connections.Server.Example
|
||||
return;
|
||||
}
|
||||
|
||||
if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024) // 5 MB
|
||||
if (new FileInfo(logFilePath).Length > 5 * 1024 * 1024)
|
||||
{
|
||||
var archiveFilePath = Path.Combine(Path.GetDirectoryName(logFilePath) ?? ".", $"server_log{DateTime.Now:yyyyMMdd_HHmmss}.txt");
|
||||
File.Move(logFilePath, archiveFilePath);
|
||||
@@ -147,10 +276,10 @@ namespace EonaCat.Connections.Server.Example
|
||||
|
||||
File.AppendAllText(logFilePath, logMessage);
|
||||
}
|
||||
catch
|
||||
catch (Exception)
|
||||
{
|
||||
// Ignore logging errors
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user