Initial version
This commit is contained in:
93
.gitignore
vendored
93
.gitignore
vendored
@@ -2,7 +2,7 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
@@ -14,9 +14,6 @@
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
@@ -24,14 +21,10 @@ mono_crash.*
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
@@ -45,10 +38,9 @@ Generated\ Files/
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
@@ -63,9 +55,6 @@ project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
@@ -83,8 +72,6 @@ StyleCopReport.xml
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
# but not Directory.Build.rsp, as it configures directory-level build defaults
|
||||
!Directory.Build.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
@@ -93,7 +80,6 @@ StyleCopReport.xml
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.tlog
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
@@ -135,6 +121,9 @@ _ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
@@ -145,11 +134,6 @@ _TeamCity*
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
@@ -197,8 +181,6 @@ PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
@@ -223,14 +205,12 @@ BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
!*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
@@ -274,9 +254,6 @@ ServiceFabricBackup/
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
@@ -297,17 +274,6 @@ node_modules/
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
||||
*.vbp
|
||||
|
||||
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
||||
*.dsw
|
||||
*.dsp
|
||||
|
||||
# Visual Studio 6 technical files
|
||||
*.ncb
|
||||
*.aps
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
@@ -323,6 +289,10 @@ paket-files/
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
@@ -364,53 +334,10 @@ ASALocalRun/
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# Visual Studio History (VSHistory) files
|
||||
.vshistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# VS Code files for those working on multiple tools
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Windows Installer files from build outputs
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
|
||||
# ---> VisualStudioCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\EonaCat.FastNetwork\EonaCat.FastNetwork.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="client.pfx">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
45
EonaCat.FastNetwork.Tester.Client/Program.cs
Normal file
45
EonaCat.FastNetwork.Tester.Client/Program.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using EonaCat.FastNetwork;
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System.Text;
|
||||
|
||||
var config = new FastNetworkConfig
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
UseAES = true,
|
||||
AESKey = "your-secret-key",
|
||||
AutoReconnect = true,
|
||||
MaxConnections = 100,
|
||||
UseSSL = true,
|
||||
Certificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection
|
||||
{
|
||||
new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss")
|
||||
}
|
||||
};
|
||||
|
||||
List<FastNetworkClient> clients = new List<FastNetworkClient>();
|
||||
var totalClients = 100;
|
||||
for (int clientNumber = 0; clientNumber < totalClients; clientNumber++)
|
||||
{
|
||||
var client = new FastNetworkClient(config);
|
||||
client.Nickname = $"Player{clientNumber}";
|
||||
client.MessageReceived += (s, data) =>
|
||||
{
|
||||
Console.WriteLine($"Received: {Encoding.UTF8.GetString(data)}");
|
||||
};
|
||||
await client.ConnectAsync("127.0.0.1", 8080);
|
||||
clients.Add(client);
|
||||
}
|
||||
Console.WriteLine($"{totalClients} clients started on port 8080");
|
||||
|
||||
var i = 0;
|
||||
while (true)
|
||||
{
|
||||
i++;
|
||||
for (int clientNumber = 0; clientNumber < totalClients; clientNumber++)
|
||||
{
|
||||
var client = clients[clientNumber];
|
||||
var randomMessage = $"RANDOM CRAP {i}";
|
||||
await client.SendAsync(Encoding.UTF8.GetBytes(randomMessage));
|
||||
}
|
||||
await Task.Delay(1000);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\EonaCat.FastNetwork\EonaCat.FastNetwork.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="server.pfx">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
35
EonaCat.FastNetwork.Tester.Server/Program.cs
Normal file
35
EonaCat.FastNetwork.Tester.Server/Program.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using EonaCat.FastNetwork;
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using ProtocolType = EonaCat.FastNetwork.Models.ProtocolType;
|
||||
|
||||
var config = new FastNetworkConfig
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
UseAES = true,
|
||||
AESKey = "your-secret-key",
|
||||
AutoReconnect = true,
|
||||
MaxConnections = 100,
|
||||
UseSSL = true,
|
||||
Certificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection
|
||||
{
|
||||
new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss")
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
var server = new FastNetworkServer(config);
|
||||
server.MessageReceived += (s, msg) => {
|
||||
Console.WriteLine($"Received from {msg.SenderId} => {Encoding.UTF8.GetString(msg.Data)}");
|
||||
server.SendToClientAsync(msg.SenderId, msg.Data).ConfigureAwait(false);
|
||||
};
|
||||
server.ClientConnected += (s, client) => {
|
||||
Console.Title = $"Connected Clients: {server.Clients.Count()}";
|
||||
Console.WriteLine($"Client {client.Id} connected");
|
||||
};
|
||||
await server.StartAsync(8080);
|
||||
Console.WriteLine("Server started on port 8080");
|
||||
Console.ReadKey();
|
||||
42
EonaCat.FastNetwork.sln
Normal file
42
EonaCat.FastNetwork.sln
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36603.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastNetwork", "EonaCat.FastNetwork\EonaCat.FastNetwork.csproj", "{4E4152E9-EDB2-48C4-B453-C3ACA105FC46}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastNetwork.Tester.Client", "EonaCat.FastNetwork.Tester.Client\EonaCat.FastNetwork.Tester.Client.csproj", "{22BFB36C-5597-4AEA-9E04-4FAB1E687D65}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastNetwork.Tester.Server", "EonaCat.FastNetwork.Tester.Server\EonaCat.FastNetwork.Tester.Server.csproj", "{26911727-D36B-45B8-A56C-D761D3486AF7}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Readme.md = Readme.md
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{4E4152E9-EDB2-48C4-B453-C3ACA105FC46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4E4152E9-EDB2-48C4-B453-C3ACA105FC46}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4E4152E9-EDB2-48C4-B453-C3ACA105FC46}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4E4152E9-EDB2-48C4-B453-C3ACA105FC46}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{22BFB36C-5597-4AEA-9E04-4FAB1E687D65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{22BFB36C-5597-4AEA-9E04-4FAB1E687D65}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{22BFB36C-5597-4AEA-9E04-4FAB1E687D65}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{22BFB36C-5597-4AEA-9E04-4FAB1E687D65}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{26911727-D36B-45B8-A56C-D761D3486AF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{26911727-D36B-45B8-A56C-D761D3486AF7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{26911727-D36B-45B8-A56C-D761D3486AF7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{26911727-D36B-45B8-A56C-D761D3486AF7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6B8B56DF-8760-4D4C-A93A-04F05B4B9ACE}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
38
EonaCat.FastNetwork/EonaCat.FastNetwork.csproj
Normal file
38
EonaCat.FastNetwork/EonaCat.FastNetwork.csproj
Normal file
@@ -0,0 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<Title>EonaCat.FastNetwork</Title>
|
||||
<Company>EonaCat (Jeroen Saey)</Company>
|
||||
<Authors>EonaCat (Jeroen Saey)</Authors>
|
||||
<Version>1.0.0</Version>
|
||||
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.FastNetwork</PackageProjectUrl>
|
||||
<Copyright>EonaCat (Jeroen Saey)</Copyright>
|
||||
<PackageIcon>EonaCat.png</PackageIcon>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.FastNetwork</RepositoryUrl>
|
||||
<PackageId>EonaCat.FastNetwork</PackageId>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<Description>A **lightweight, asynchronous, and secure networking framework** for C# that provides TCP and UDP client-server communication with built-in **AES encryption**, **SSL/TLS support**, **auto-reconnection**, and **heartbeat monitoring**.</Description>
|
||||
<PackageReleaseNotes>A **lightweight, asynchronous, and secure networking framework** for C# that provides TCP and UDP client-server communication with built-in **AES encryption**, **SSL/TLS support**, **auto-reconnection**, and **heartbeat monitoring**.</PackageReleaseNotes>
|
||||
<PackageTags>EonaCat, TCP, UDP, Sockets, Auto Reconnect, SSL, AES, Secure, Fast, 100k connections, Speed, Jeroen, Saey</PackageTags>
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="..\EonaCat.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
<None Include="..\LICENSE">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
<None Include="..\README.md">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
287
EonaCat.FastNetwork/FastNetworkClient.cs
Normal file
287
EonaCat.FastNetwork/FastNetworkClient.cs
Normal file
@@ -0,0 +1,287 @@
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ProtocolType = EonaCat.FastNetwork.Models.ProtocolType;
|
||||
|
||||
namespace EonaCat.FastNetwork
|
||||
{
|
||||
public class FastNetworkClient
|
||||
{
|
||||
private readonly FastNetworkConfig _config;
|
||||
private TcpClient _tcpClient;
|
||||
private UdpClient _udpClient;
|
||||
private Stream _stream;
|
||||
private IPEndPoint _serverEndPoint;
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
private int _reconnectAttempts;
|
||||
private readonly AESEncryption _aes;
|
||||
|
||||
public string ClientId { get; private set; }
|
||||
public string Nickname { get; set; }
|
||||
public ConnectionState State { get; private set; }
|
||||
public long BytesSent { get; private set; }
|
||||
public long BytesReceived { get; private set; }
|
||||
|
||||
public event EventHandler<ConnectionState> StateChanged;
|
||||
public event EventHandler<byte[]> MessageReceived;
|
||||
public event EventHandler<string> ErrorOccurred;
|
||||
|
||||
public FastNetworkClient(FastNetworkConfig config)
|
||||
{
|
||||
_config = config ?? new FastNetworkConfig();
|
||||
ClientId = Guid.NewGuid().ToString();
|
||||
State = ConnectionState.Disconnected;
|
||||
|
||||
if (_config.UseAES && !string.IsNullOrEmpty(_config.AESKey))
|
||||
{
|
||||
_aes = new AESEncryption(_config.AESKey);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ConnectAsync(string host, int port)
|
||||
{
|
||||
if (State == ConnectionState.Connected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ChangeState(ConnectionState.Connecting);
|
||||
_serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
|
||||
|
||||
try
|
||||
{
|
||||
if (_config.Protocol == ProtocolType.TCP)
|
||||
{
|
||||
await ConnectTcpAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
ConnectUdp();
|
||||
}
|
||||
|
||||
_reconnectAttempts = 0;
|
||||
ChangeState(ConnectionState.Connected);
|
||||
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
_ = ReceiveDataAsync(_cancellationTokenSource.Token);
|
||||
|
||||
if (_config.HeartbeatIntervalMs > 0)
|
||||
{
|
||||
_ = SendHeartbeatAsync(_cancellationTokenSource.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Connection error: {ex.Message}");
|
||||
ChangeState(ConnectionState.Failed);
|
||||
|
||||
if (_config.AutoReconnect)
|
||||
{
|
||||
_ = ReconnectAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConnectTcpAsync()
|
||||
{
|
||||
_tcpClient = new TcpClient();
|
||||
await _tcpClient.ConnectAsync(_serverEndPoint.Address, _serverEndPoint.Port);
|
||||
|
||||
Stream stream = _tcpClient.GetStream();
|
||||
|
||||
if (_config.UseSSL)
|
||||
{
|
||||
var sslStream = new SslStream(stream, false, (sender, cert, chain, errors) => true);
|
||||
await sslStream.AuthenticateAsClientAsync(_serverEndPoint.Address.ToString(), clientCertificates: _config.Certificates, false);
|
||||
stream = sslStream;
|
||||
}
|
||||
|
||||
_stream = stream;
|
||||
}
|
||||
|
||||
private void ConnectUdp()
|
||||
{
|
||||
_udpClient = new UdpClient();
|
||||
_udpClient.Connect(_serverEndPoint);
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync()
|
||||
{
|
||||
_cancellationTokenSource?.Cancel();
|
||||
|
||||
_stream?.Dispose();
|
||||
_tcpClient?.Close();
|
||||
_udpClient?.Close();
|
||||
|
||||
ChangeState(ConnectionState.Disconnected);
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task SendAsync(byte[] data)
|
||||
{
|
||||
if (State != ConnectionState.Connected)
|
||||
{
|
||||
throw new InvalidOperationException("Client is not connected");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Encrypt(data);
|
||||
}
|
||||
|
||||
if (_config.Protocol == ProtocolType.TCP)
|
||||
{
|
||||
await _stream.WriteAsync(data, 0, data.Length);
|
||||
await _stream.FlushAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
await _udpClient.SendAsync(data, data.Length);
|
||||
}
|
||||
|
||||
BytesSent += data.Length;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Send error: {ex.Message}");
|
||||
|
||||
if (_config.AutoReconnect)
|
||||
{
|
||||
_ = ReconnectAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveDataAsync(CancellationToken token)
|
||||
{
|
||||
var buffer = new byte[_config.BufferSize];
|
||||
|
||||
while (!token.IsCancellationRequested && State == ConnectionState.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_config.Protocol == ProtocolType.TCP)
|
||||
{
|
||||
var bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, token);
|
||||
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
if (_config.AutoReconnect)
|
||||
{
|
||||
_ = ReconnectAsync();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Array.Copy(buffer, data, bytesRead);
|
||||
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Decrypt(data);
|
||||
}
|
||||
|
||||
BytesReceived += bytesRead;
|
||||
MessageReceived?.Invoke(this, data);
|
||||
}
|
||||
else
|
||||
{
|
||||
var result = await _udpClient.ReceiveAsync();
|
||||
var data = result.Buffer;
|
||||
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Decrypt(data);
|
||||
}
|
||||
|
||||
BytesReceived += data.Length;
|
||||
MessageReceived?.Invoke(this, data);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Receive error: {ex.Message}");
|
||||
|
||||
if (_config.AutoReconnect)
|
||||
{
|
||||
_ = ReconnectAsync();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReconnectAsync()
|
||||
{
|
||||
if (State == ConnectionState.Reconnecting)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_config.MaxReconnectAttempts > 0 && _reconnectAttempts >= _config.MaxReconnectAttempts)
|
||||
{
|
||||
ChangeState(ConnectionState.Failed);
|
||||
return;
|
||||
}
|
||||
|
||||
ChangeState(ConnectionState.Reconnecting);
|
||||
_reconnectAttempts++;
|
||||
|
||||
await Task.Delay(_config.ReconnectDelayMs);
|
||||
|
||||
try
|
||||
{
|
||||
await DisconnectAsync();
|
||||
await ConnectAsync(_serverEndPoint.Address.ToString(), _serverEndPoint.Port);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (_config.AutoReconnect)
|
||||
{
|
||||
_ = ReconnectAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && State == ConnectionState.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(_config.HeartbeatIntervalMs, token);
|
||||
await SendAsync(Encoding.UTF8.GetBytes("HEARTBEAT"));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ChangeState(ConnectionState newState)
|
||||
{
|
||||
if (State != newState)
|
||||
{
|
||||
State = newState;
|
||||
StateChanged?.Invoke(this, newState);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
372
EonaCat.FastNetwork/FastNetworkServer.cs
Normal file
372
EonaCat.FastNetwork/FastNetworkServer.cs
Normal file
@@ -0,0 +1,372 @@
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ProtocolType = EonaCat.FastNetwork.Models.ProtocolType;
|
||||
|
||||
namespace EonaCat.FastNetwork
|
||||
{
|
||||
public class FastNetworkServer
|
||||
{
|
||||
private readonly FastNetworkConfig _config;
|
||||
private TcpListener _tcpListener;
|
||||
private UdpClient _udpListener;
|
||||
private readonly ConcurrentDictionary<string, ConnectedClient> _clients;
|
||||
private readonly ConcurrentDictionary<string, string> _nicknameToId;
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
private bool _isRunning;
|
||||
private readonly AESEncryption _aes;
|
||||
private readonly SemaphoreSlim _connectionSemaphore;
|
||||
|
||||
public event EventHandler<ClientInfo> ClientConnected;
|
||||
public event EventHandler<ClientInfo> ClientDisconnected;
|
||||
public event EventHandler<FastNetworkMessage> MessageReceived;
|
||||
public event EventHandler<string> ErrorOccurred;
|
||||
|
||||
public int ConnectedClientsCount => _clients.Count;
|
||||
public IEnumerable<ClientInfo> Clients => _clients.Values.Select(c => c.Info);
|
||||
|
||||
public FastNetworkServer(FastNetworkConfig config)
|
||||
{
|
||||
_config = config ?? new FastNetworkConfig();
|
||||
_clients = new ConcurrentDictionary<string, ConnectedClient>();
|
||||
_nicknameToId = new ConcurrentDictionary<string, string>();
|
||||
_connectionSemaphore = new SemaphoreSlim(_config.MaxConnections, _config.MaxConnections);
|
||||
|
||||
if (_config.UseAES && !string.IsNullOrEmpty(_config.AESKey))
|
||||
{
|
||||
_aes = new AESEncryption(_config.AESKey);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StartAsync(int port)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
_isRunning = true;
|
||||
|
||||
try
|
||||
{
|
||||
if (_config.Protocol == ProtocolType.TCP)
|
||||
{
|
||||
_tcpListener = new TcpListener(IPAddress.Any, port);
|
||||
_tcpListener.Start();
|
||||
_ = AcceptTcpClientsAsync(_cancellationTokenSource.Token);
|
||||
}
|
||||
else
|
||||
{
|
||||
_udpListener = new UdpClient(port);
|
||||
_ = ReceiveUdpDataAsync(_cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
_ = MonitorClientsAsync(_cancellationTokenSource.Token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Server start error: {ex.Message}");
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isRunning = false;
|
||||
_cancellationTokenSource?.Cancel();
|
||||
|
||||
foreach (var client in _clients.Values.ToList())
|
||||
{
|
||||
await DisconnectClientAsync(client.Info.Id);
|
||||
}
|
||||
|
||||
_tcpListener?.Stop();
|
||||
_udpListener?.Close();
|
||||
}
|
||||
|
||||
private async Task AcceptTcpClientsAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _connectionSemaphore.WaitAsync(token);
|
||||
|
||||
var tcpClient = await _tcpListener.AcceptTcpClientAsync();
|
||||
_ = HandleTcpClientAsync(tcpClient, token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Accept client error: {ex.Message}");
|
||||
_connectionSemaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleTcpClientAsync(TcpClient tcpClient, CancellationToken token)
|
||||
{
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
var client = new ConnectedClient
|
||||
{
|
||||
Id = clientId,
|
||||
TcpClient = tcpClient,
|
||||
Info = new ClientInfo
|
||||
{
|
||||
Id = clientId,
|
||||
RemoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint,
|
||||
ConnectedAt = DateTime.UtcNow,
|
||||
LastActivity = DateTime.UtcNow,
|
||||
State = ConnectionState.Connected
|
||||
}
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
Stream stream = tcpClient.GetStream();
|
||||
|
||||
if (_config.UseSSL && _config.Certificates != null)
|
||||
{
|
||||
var sslStream = new SslStream(stream, false);
|
||||
await sslStream.AuthenticateAsServerAsync(_config.Certificates[0]);
|
||||
stream = sslStream;
|
||||
}
|
||||
|
||||
client.Stream = stream;
|
||||
_clients.TryAdd(clientId, client);
|
||||
ClientConnected?.Invoke(this, client.Info);
|
||||
|
||||
await ReceiveTcpDataAsync(client, token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Client {clientId} error: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await DisconnectClientAsync(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveTcpDataAsync(ConnectedClient client, CancellationToken token)
|
||||
{
|
||||
var buffer = new byte[_config.BufferSize];
|
||||
|
||||
while (!token.IsCancellationRequested && client.TcpClient.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytesRead = await client.Stream.ReadAsync(buffer, 0, buffer.Length, token);
|
||||
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
client.Info.LastActivity = DateTime.UtcNow;
|
||||
client.Info.BytesReceived += bytesRead;
|
||||
|
||||
var data = new byte[bytesRead];
|
||||
Array.Copy(buffer, data, bytesRead);
|
||||
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Decrypt(data);
|
||||
}
|
||||
|
||||
var message = new FastNetworkMessage
|
||||
{
|
||||
SenderId = client.Info.Id,
|
||||
Data = data,
|
||||
Timestamp = DateTime.UtcNow
|
||||
};
|
||||
|
||||
MessageReceived?.Invoke(this, message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Receive error from {client.Info.Id}: {ex.Message}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReceiveUdpDataAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _udpListener.ReceiveAsync();
|
||||
var data = result.Buffer;
|
||||
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Decrypt(data);
|
||||
}
|
||||
|
||||
var clientKey = result.RemoteEndPoint.ToString();
|
||||
|
||||
var message = new FastNetworkMessage
|
||||
{
|
||||
SenderId = clientKey,
|
||||
Data = data,
|
||||
Timestamp = DateTime.UtcNow
|
||||
};
|
||||
|
||||
MessageReceived?.Invoke(this, message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"UDP receive error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SendToClientAsync(string clientId, byte[] data)
|
||||
{
|
||||
if (!_clients.TryGetValue(clientId, out var client))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_config.UseAES && _aes != null)
|
||||
{
|
||||
data = _aes.Encrypt(data);
|
||||
}
|
||||
|
||||
if (_config.Protocol == ProtocolType.TCP)
|
||||
{
|
||||
await client.Stream.WriteAsync(data, 0, data.Length);
|
||||
await client.Stream.FlushAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
await _udpListener.SendAsync(data, data.Length, client.Info.RemoteEndPoint);
|
||||
}
|
||||
|
||||
client.Info.BytesSent += data.Length;
|
||||
client.Info.LastActivity = DateTime.UtcNow;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Send error to {clientId}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task BroadcastAsync(byte[] data, string excludeClientId = null)
|
||||
{
|
||||
var tasks = _clients.Values
|
||||
.Where(c => c.Id != excludeClientId)
|
||||
.Select(c => SendToClientAsync(c.Id, data));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public bool SetNickname(string clientId, string nickname)
|
||||
{
|
||||
if (!_clients.TryGetValue(clientId, out var client))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove old nickname mapping
|
||||
if (!string.IsNullOrEmpty(client.Info.Nickname))
|
||||
{
|
||||
_nicknameToId.TryRemove(client.Info.Nickname, out _);
|
||||
}
|
||||
|
||||
client.Info.Nickname = nickname;
|
||||
_nicknameToId[nickname] = clientId;
|
||||
return true;
|
||||
}
|
||||
|
||||
public string GetClientIdByNickname(string nickname)
|
||||
{
|
||||
_nicknameToId.TryGetValue(nickname, out var clientId);
|
||||
return clientId;
|
||||
}
|
||||
|
||||
private async Task DisconnectClientAsync(string clientId)
|
||||
{
|
||||
if (_clients.TryRemove(clientId, out var client))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(client.Info.Nickname))
|
||||
{
|
||||
_nicknameToId.TryRemove(client.Info.Nickname, out _);
|
||||
}
|
||||
|
||||
client.Stream?.Dispose();
|
||||
client.TcpClient?.Close();
|
||||
|
||||
ClientDisconnected?.Invoke(this, client.Info);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_connectionSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task MonitorClientsAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(_config.HeartbeatIntervalMs, token);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var timeoutClients = _clients.Values
|
||||
.Where(c => (now - c.Info.LastActivity).TotalMilliseconds > _config.TimeoutMs)
|
||||
.ToList();
|
||||
|
||||
foreach (var client in timeoutClients)
|
||||
{
|
||||
await DisconnectClientAsync(client.Id);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorOccurred?.Invoke(this, $"Monitor error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class ConnectedClient
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public TcpClient TcpClient { get; set; }
|
||||
public Stream Stream { get; set; }
|
||||
public ClientInfo Info { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
58
EonaCat.FastNetwork/Models/AESEncryption.cs
Normal file
58
EonaCat.FastNetwork/Models/AESEncryption.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public class AESEncryption
|
||||
{
|
||||
private readonly byte[] _key;
|
||||
private readonly byte[] _iv;
|
||||
|
||||
public AESEncryption(string key)
|
||||
{
|
||||
using (var sha = SHA256.Create())
|
||||
{
|
||||
_key = sha.ComputeHash(Encoding.UTF8.GetBytes(key));
|
||||
}
|
||||
_iv = new byte[16];
|
||||
}
|
||||
|
||||
public byte[] Encrypt(byte[] data)
|
||||
{
|
||||
using (var aes = Aes.Create())
|
||||
{
|
||||
aes.Key = _key;
|
||||
aes.IV = _iv;
|
||||
|
||||
using (var encryptor = aes.CreateEncryptor())
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
||||
{
|
||||
cs.Write(data, 0, data.Length);
|
||||
}
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] Decrypt(byte[] data)
|
||||
{
|
||||
using (var aes = Aes.Create())
|
||||
{
|
||||
aes.Key = _key;
|
||||
aes.IV = _iv;
|
||||
|
||||
using (var decryptor = aes.CreateDecryptor())
|
||||
using (var ms = new MemoryStream(data))
|
||||
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
|
||||
using (var result = new MemoryStream())
|
||||
{
|
||||
cs.CopyTo(result);
|
||||
return result.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
EonaCat.FastNetwork/Models/ClientInfo.cs
Normal file
19
EonaCat.FastNetwork/Models/ClientInfo.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public class ClientInfo
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public string Nickname { get; set; }
|
||||
public IPEndPoint RemoteEndPoint { get; set; }
|
||||
public DateTime ConnectedAt { get; set; }
|
||||
public DateTime LastActivity { get; set; }
|
||||
public long BytesSent { get; set; }
|
||||
public long BytesReceived { get; set; }
|
||||
public ConnectionState State { get; set; }
|
||||
public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
11
EonaCat.FastNetwork/Models/ConnectionState.cs
Normal file
11
EonaCat.FastNetwork/Models/ConnectionState.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public enum ConnectionState
|
||||
{
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Connected,
|
||||
Reconnecting,
|
||||
Failed
|
||||
}
|
||||
}
|
||||
21
EonaCat.FastNetwork/Models/FastNetworkConfig.cs
Normal file
21
EonaCat.FastNetwork/Models/FastNetworkConfig.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public class FastNetworkConfig
|
||||
{
|
||||
public ProtocolType Protocol { get; set; } = ProtocolType.TCP;
|
||||
public bool UseSSL { get; set; } = false;
|
||||
public X509CertificateCollection Certificates { get; set; }
|
||||
public bool UseAES { get; set; } = false;
|
||||
public string AESKey { get; set; } = null;
|
||||
public bool AutoReconnect { get; set; } = true;
|
||||
public int ReconnectDelayMs { get; set; } = 3000;
|
||||
public int MaxReconnectAttempts { get; set; } = -1; // -1 = infinite
|
||||
public int BufferSize { get; set; } = 8192;
|
||||
public int MaxConnections { get; set; } = 100000;
|
||||
public bool UseCompression { get; set; } = false;
|
||||
public int HeartbeatIntervalMs { get; set; } = 30000;
|
||||
public int TimeoutMs { get; set; } = 60000;
|
||||
}
|
||||
}
|
||||
13
EonaCat.FastNetwork/Models/FastNetworkMessage.cs
Normal file
13
EonaCat.FastNetwork/Models/FastNetworkMessage.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public class FastNetworkMessage
|
||||
{
|
||||
public string SenderId { get; set; }
|
||||
public string RecipientId { get; set; }
|
||||
public byte[] Data { get; set; }
|
||||
public DateTime Timestamp { get; set; }
|
||||
public bool IsSystemMessage { get; set; }
|
||||
}
|
||||
}
|
||||
8
EonaCat.FastNetwork/ProtocolType.cs
Normal file
8
EonaCat.FastNetwork/ProtocolType.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace EonaCat.FastNetwork.Models
|
||||
{
|
||||
public enum ProtocolType
|
||||
{
|
||||
TCP,
|
||||
UDP
|
||||
}
|
||||
}
|
||||
BIN
EonaCat.ico
Normal file
BIN
EonaCat.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 248 KiB |
BIN
EonaCat.png
Normal file
BIN
EonaCat.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 88 KiB |
213
LICENSE
213
LICENSE
@@ -1,73 +1,204 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
https://EonaCat.com/license/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
OF SOFTWARE BY EONACAT (JEROEN SAEY)
|
||||
|
||||
1. Definitions.
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 EonaCat
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
159
README.md
159
README.md
@@ -1,3 +1,158 @@
|
||||
# EonaCat.FastNetwork
|
||||
# 🔥 EonaCat.FastNetwork 🔥
|
||||
|
||||
A **lightweight, asynchronous, and secure networking framework** for C# that provides TCP and UDP client-server communication with built-in **AES encryption**, **SSL/TLS support**, **auto-reconnection**, and **heartbeat monitoring**.
|
||||
|
||||
This project contains:
|
||||
- `FastNetworkClient` — A configurable client capable of connecting to servers over TCP or UDP.
|
||||
- `FastNetworkServer` — A high-performance server capable of managing multiple clients, broadcasting messages, and monitoring connections.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Features
|
||||
|
||||
✅ Supports both **TCP** and **UDP** communication
|
||||
✅ **Asynchronous I/O** with `async/await`
|
||||
✅ Optional **AES encryption** for secure communication
|
||||
✅ Optional **SSL/TLS** (via `SslStream`)
|
||||
✅ **Automatic reconnection** logic for clients
|
||||
✅ **Heartbeat system** for connection health checks
|
||||
✅ **Client nickname management**
|
||||
✅ **Server broadcasting and targeted messaging**
|
||||
✅ **Configurable limits** (buffer size, timeouts, max connections, etc.)
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
Both the client and server use a `FastNetworkConfig` object to control behavior.
|
||||
|
||||
### Example Configuration
|
||||
```csharp
|
||||
var config = new FastNetworkConfig
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
UseAES = true,
|
||||
AESKey = "your-256-bit-key",
|
||||
UseSSL = false,
|
||||
AutoReconnect = true,
|
||||
HeartbeatIntervalMs = 5000,
|
||||
ReconnectDelayMs = 3000,
|
||||
MaxReconnectAttempts = 5,
|
||||
TimeoutMs = 10000,
|
||||
BufferSize = 4096
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
💻 Usage:
|
||||
|
||||
🤩 Server Example
|
||||
|
||||
```csharp
|
||||
using EonaCat.FastNetwork;
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
class Program
|
||||
{
|
||||
static async Task Main()
|
||||
{
|
||||
var config = new FastNetworkConfig
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
UseAES = true,
|
||||
AESKey = "your-256-bit-key",
|
||||
AutoReconnect = true
|
||||
};
|
||||
|
||||
var server = new FastNetworkServer(config);
|
||||
|
||||
server.ClientConnected += (s, info) =>
|
||||
{
|
||||
Console.WriteLine($"Client connected: {info.Id} ({info.RemoteEndPoint})");
|
||||
};
|
||||
|
||||
server.MessageReceived += async (s, msg) =>
|
||||
{
|
||||
Console.WriteLine($"Message from {msg.SenderId}: {Encoding.UTF8.GetString(msg.Data)}");
|
||||
await server.SendToClientAsync(msg.SenderId, Encoding.UTF8.GetBytes("Message received!"));
|
||||
};
|
||||
|
||||
server.ClientDisconnected += (s, info) =>
|
||||
{
|
||||
Console.WriteLine($"Client disconnected: {info.Id}");
|
||||
};
|
||||
|
||||
await server.StartAsync(5000);
|
||||
Console.WriteLine("Server running on port 5000...");
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
😋 Client Example
|
||||
```csharp
|
||||
using EonaCat.FastNetwork;
|
||||
using EonaCat.FastNetwork.Models;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
class Program
|
||||
{
|
||||
static async Task Main()
|
||||
{
|
||||
var config = new FastNetworkConfig
|
||||
{
|
||||
Protocol = ProtocolType.TCP,
|
||||
UseAES = true,
|
||||
AESKey = "your-256-bit-key",
|
||||
AutoReconnect = true
|
||||
};
|
||||
|
||||
var client = new FastNetworkClient(config);
|
||||
|
||||
client.StateChanged += (s, state) =>
|
||||
{
|
||||
Console.WriteLine($"Client state: {state}");
|
||||
};
|
||||
|
||||
client.MessageReceived += (s, data) =>
|
||||
{
|
||||
Console.WriteLine($"Received: {Encoding.UTF8.GetString(data)}");
|
||||
};
|
||||
|
||||
await client.ConnectAsync("127.0.0.1", 5000);
|
||||
Console.WriteLine("Connected to server.");
|
||||
|
||||
await client.SendAsync(Encoding.UTF8.GetBytes("Hello Server!"));
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
🔒 Security Options
|
||||
|
||||
🐦🔥AES Encryption
|
||||
|
||||
Enable AES encryption by setting:
|
||||
|
||||
```csharp
|
||||
config.UseAES = true;
|
||||
config.AESKey = "your-256-bit-secret-key";
|
||||
```
|
||||
|
||||
🦅SSL/TLS
|
||||
|
||||
Enable SSL by providing a certificate:
|
||||
```csharp
|
||||
config.UseSSL = true;
|
||||
config.Certificates = new[] { yourX509Certificate };
|
||||
```
|
||||
|
||||
🔁 Auto-Reconnect & Heartbeat
|
||||
|
||||
The client will automatically attempt to reconnect if the connection fails, if AutoReconnect = true.
|
||||
|
||||
The server uses heartbeats and timeouts to monitor inactive clients and disconnect them.
|
||||
|
||||
EonaCat.FastNetwork
|
||||
Reference in New Issue
Block a user