Skip to content

Commit a96ea6d

Browse files
committed
bug fixed stability update
1 parent 18a7f21 commit a96ea6d

36 files changed

+841
-469
lines changed

Benchmarks/RelayBenchmark/Program.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -183,17 +183,24 @@ private static void SerializerTest()
183183

184184
private static void RelayTest()
185185
{
186+
186187
//string ip = "79.52.134.220";
187188
string ip = "127.0.0.1";
188189

189190

190191
var cert = new X509Certificate2("client.pfx", "greenpass");
191192
var scert = new X509Certificate2("server.pfx", "greenpass");
192-
//var server = new SecureProtoRelayServer(20020, scert);
193-
//server.StartServer();
193+
if (Console.ReadLine() == "e")
194+
{
195+
var server = new SecureProtoRelayServer(20020, scert);
196+
server.StartServer();
197+
Task.Run(async () => { while (true) { await Task.Delay(5000); server.GetTcpStatistics(out var generalStats, out _); Console.WriteLine(generalStats.ToString()); } });
198+
199+
}
200+
Console.ReadLine();
194201
//Task.Run(async () => { while (true) { await Task.Delay(10000); server.GetTcpStatistics(out var generalStats, out _); Console.WriteLine(generalStats.ToString()); } });
195202
var clients = new List<RelayClient>();
196-
int numclients = 30;
203+
int numclients = 100;
197204
var pending = new Task[numclients];
198205
Task.Run(async () => { while (true) { await Task.Delay(1000); Console.WriteLine(Interlocked.Exchange(ref sumsum, 0).ToString("N0")); } });
199206

@@ -208,7 +215,7 @@ private static void RelayTest()
208215
try
209216
{
210217
pending[i] = client.ConnectAsync(ip, 20020);
211-
client.StartPingService();
218+
// client.StartPingService();
212219
// client.Connect(ip, 20011);
213220
clients.Add(client);
214221
//client.StartPingService();
@@ -235,8 +242,8 @@ private static void RelayTest()
235242
if (peer.Key == Guid.Empty)
236243
throw new Exception();
237244

238-
var a = client.RequestTcpHolePunchAsync(peer.Key);
239-
pndg.Add(a);
245+
//var a = client.RequestTcpHolePunchAsync(peer.Key);
246+
//pndg.Add(a);
240247
// var aa = client.RequestHolePunchAsync(peer.Key, 10000, false);
241248
//pndg.Add(aa);
242249
//client.TestHP(peer.Key, 10000, false);
@@ -258,13 +265,13 @@ private static void RelayTest()
258265
var testMessage = new MessageEnvelope()
259266
{
260267
Header = "Test",
261-
Payload = new byte[320]
268+
Payload = new byte[32]
262269
};
263270
for (int i = 0; i < testMessage.PayloadCount; i++)
264271
{
265272
testMessage.Payload[i] = (byte)i;
266273
}
267-
for (int i = 0; i < 1; i++)
274+
for (int i = 0; i < 100; i++)
268275
{
269276
//return;
270277
foreach (var peer in client.Peers.Keys)

Benchmarks/SslBenchmark/SslBenchmark.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net7.0</TargetFramework>
5+
<TargetFramework>net8.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
8+
<PublishAot>False</PublishAot>
89
</PropertyGroup>
910

1011
<ItemGroup>

Benchmarks/TcpBenchmark/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ private static void InitializeClients()
115115
}
116116
Task.WaitAll(toWait);
117117
Console.WriteLine("All Clients Connected");
118-
Console.WriteLine(server.SessionCount);
118+
Console.WriteLine(server?.SessionCount);
119119

120120
}
121121

Benchmarks/TcpBenchmark/TcpMessageBenchmark.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
<TargetFramework>net8.0</TargetFramework>
66
<Nullable>enable</Nullable>
77
<Platforms>AnyCPU;ARM32</Platforms>
8+
<PublishAot>False</PublishAot>
89
</PropertyGroup>
910

1011
<ItemGroup>

NetworkLibrary/Components/BufferPool.cs

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
using System.Runtime.CompilerServices;
77
using System.Threading;
88
using System.Runtime.InteropServices;
9+
using System.Threading.Tasks;
10+
911
#if NET5_0_OR_GREATER
1012
using System.Runtime.Intrinsics.Arm;
1113
using System.Runtime.Intrinsics.X86;
@@ -24,12 +26,12 @@ namespace NetworkLibrary
2426
*/
2527
public class BufferPool
2628
{
29+
static ConcurrentDictionary<byte[], string> AAA = new ConcurrentDictionary<byte[], string>();
2730
public static bool ForceGCOnCleanup = true;
2831
public static int MaxMemoryBeforeForceGc = 100000000;
2932
public const int MaxBufferSize = 1073741824;
3033
public const int MinBufferSize = 256;
31-
private static readonly ConcurrentBag<WeakReference<byte[]>> weakReferencePool = new ConcurrentBag<WeakReference<byte[]>>();
32-
private static readonly ConcurrentBag<WeakReference<byte[]>>[] bufferBuckets = new ConcurrentBag<WeakReference<byte[]>>[32];
34+
private static readonly ConcurrentBag<byte[]>[] bufferBuckets = new ConcurrentBag<byte[]>[32];
3335
private static SortedDictionary<int, int> bucketCapacityLimits = new SortedDictionary<int, int>()
3436
{
3537
{ 256,10000 },
@@ -63,9 +65,8 @@ public class BufferPool
6365

6466
static BufferPool()
6567
{
66-
Init();
67-
memoryMaintainer = new Thread(MaintainMemory);
68-
memoryMaintainer.Priority = ThreadPriority.Lowest;
68+
Init();
69+
MaintainMemory();
6970
}
7071

7172
/// <summary>
@@ -94,25 +95,24 @@ private static void Init()
9495
//bufferBuckets = new ConcurrentDictionary<int, ConcurrentBag<byte[]>>();
9596
for (int i = 8; i < 31; i++)
9697
{
97-
bufferBuckets[i] = new ConcurrentBag<WeakReference<byte[]>>();
98+
bufferBuckets[i] = new ConcurrentBag<byte[]>();
9899
}
99100
}
100101

101-
private static void MaintainMemory()
102+
private static async void MaintainMemory()
102103
{
103-
var lastTime = process.TotalProcessorTime;
104104
while (true)
105105
{
106-
autoGcHandle.WaitOne();
107-
Thread.Sleep(10000);
108-
var currentProcTime = process.TotalProcessorTime;
109-
var deltaT = (lastTime - currentProcTime).TotalMilliseconds;
110-
lastTime = currentProcTime;
111-
112-
if (deltaT < 100 && process.WorkingSet64 < MaxMemoryBeforeForceGc)
113-
GC.Collect();
106+
await Task.Delay(10000);
107+
for (int i = 8; i < 31; i++)
108+
{
109+
while(bufferBuckets[i].Count> bucketCapacityLimits[GetBucketSize(i)])
110+
{
111+
if(bufferBuckets[i].TryTake(out var buffer))
112+
AAA.TryRemove(buffer, out _);
113+
}
114+
}
114115
}
115-
116116
}
117117

118118

@@ -125,6 +125,7 @@ private static void MaintainMemory()
125125
[MethodImpl(MethodImplOptions.AggressiveInlining)]
126126
public static byte[] RentBuffer(int size)
127127
{
128+
//return new byte[size];
128129
byte[] buffer;
129130
if (MaxBufferSize < size)
130131
throw new InvalidOperationException(
@@ -133,13 +134,10 @@ public static byte[] RentBuffer(int size)
133134

134135
int idx = GetBucketIndex(size);
135136

136-
while (bufferBuckets[idx].TryTake(out WeakReference<byte[]> bufferRef))
137+
if (bufferBuckets[idx].TryTake(out buffer))
137138
{
138-
if (bufferRef.TryGetTarget(out buffer))
139-
{
140-
weakReferencePool.Add(bufferRef);
141-
return buffer;
142-
}
139+
AAA.TryRemove(buffer,out _);
140+
return buffer;
143141
}
144142

145143
buffer = ByteCopy.GetNewArray(GetBucketSize(idx));
@@ -156,15 +154,14 @@ public static void ReturnBuffer(byte[] buffer)
156154
{
157155
if (buffer.Length <= MinBufferSize) return;
158156

159-
int idx = GetBucketIndex(buffer.Length);
160-
if (weakReferencePool.TryTake(out var wr))
157+
if (!AAA.TryAdd(buffer, null))
161158
{
162-
wr.SetTarget(buffer);
163-
bufferBuckets[idx - 1].Add(wr);
164-
159+
MiniLogger.Log(MiniLogger.LogLevel.Error, "Buffer Pool Duplicated return detected");
160+
return;
165161
}
166-
else
167-
bufferBuckets[idx - 1].Add(new WeakReference<byte[]>(buffer));
162+
163+
int idx = GetBucketIndex(buffer.Length);
164+
bufferBuckets[idx - 1].Add(buffer);
168165
buffer = null;
169166
}
170167

NetworkLibrary/Components/ByteMessageReader.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Runtime.CompilerServices;
3+
using System.Threading;
34

45
namespace NetworkLibrary.Components
56
{
@@ -225,10 +226,17 @@ private void FreeMemory()
225226
BufferPool.ReturnBuffer(internalBufer);
226227
internalBufer = BufferPool.RentBuffer(originalCapacity);
227228
}
228-
229+
229230
public void ReleaseResources()
230231
{
231-
if (internalBufer != null) { BufferPool.ReturnBuffer(internalBufer); internalBufer = null; }
232+
OnMessageReady = null;
233+
234+
var b = Interlocked.Exchange(ref internalBufer, null);
235+
236+
if (b != null)
237+
{
238+
BufferPool.ReturnBuffer(b);
239+
}
232240
}
233241
#endregion
234242
}

NetworkLibrary/Components/ConcurrentAesAlgorithm.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ private IAesEngine GetEngine(byte val)
5454
return noEncryption;
5555

5656
default:
57-
throw new NotSupportedException(val.ToString());
57+
throw new NotImplementedException(val.ToString()+" - type of encryption algorithm is not implemented");
5858
}
5959
}
6060
public byte[] Decrypt(byte[] bytes) => Decrypt(bytes, 0, bytes.Length);

NetworkLibrary/Components/PooledMemoryStream.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.IO;
33
using System.Runtime.CompilerServices;
4+
using System.Threading;
45

56
namespace NetworkLibrary.Components
67
{
@@ -70,7 +71,7 @@ public override void Flush()
7071
public void Clear()
7172
{
7273
position = 0;
73-
if (bufferInternal.Length > 128000)
74+
if (bufferInternal.Length > 512000)
7475
{
7576
BufferPool.ReturnBuffer(bufferInternal);
7677
bufferInternal = BufferPool.RentBuffer(128000);
@@ -361,8 +362,11 @@ protected override void Dispose(bool disposing)
361362
{
362363
if (disposing)
363364
{
364-
BufferPool.ReturnBuffer(bufferInternal);
365-
bufferInternal = null;
365+
var buf = Interlocked.Exchange(ref bufferInternal, null);
366+
if (buf!=null)
367+
{
368+
BufferPool.ReturnBuffer(buf);
369+
}
366370
}
367371
base.Dispose(disposing);
368372
}

NetworkLibrary/MessageProtocol/Fast/Network/MessageClient.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, G
5252
ses.MaxIndexedMemory = MaxIndexedMemory;
5353
ses.DropOnCongestion = DropOnCongestion;
5454
ses.OnSessionClosed += (id) => OnDisconnected?.Invoke();
55+
ses.UseQueue = false;
5556
session = ses;
5657

5758

NetworkLibrary/MessageProtocol/Fast/Network/MessageSession.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System;
44
using System.Net.Sockets;
55
using System.Runtime.CompilerServices;
6+
using System.Threading;
67

78
namespace NetworkLibrary.MessageProtocol
89
{
@@ -127,9 +128,8 @@ private void SendAsyncInternal<T>(MessageEnvelope envelope, T message)
127128
protected override void ReleaseReceiveResources()
128129
{
129130
base.ReleaseReceiveResources();
130-
reader.ReleaseResources();
131-
reader = null;
132-
mq = null;
131+
Interlocked.Exchange(ref mq, null)?.Dispose();
132+
Interlocked.Exchange(ref reader, null)?.ReleaseResources();
133133
}
134134
}
135135
}

0 commit comments

Comments
 (0)