Skip to content

Commit f82618a

Browse files
Merge pull request #21 from ReferenceType/develop
Develop
2 parents ba4cdd4 + fbd1e98 commit f82618a

File tree

22 files changed

+440
-180
lines changed

22 files changed

+440
-180
lines changed

Benchmarks/RelayBenchmark/Program.cs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ private static void SerializerTest()
180180
static Stopwatch sw = new Stopwatch();
181181
private static void RelayTest()
182182
{
183-
//string ip = "79.19.128.177";
183+
//string ip = "79.52.134.220";
184184
string ip = "127.0.0.1";
185185

186186

@@ -190,13 +190,14 @@ private static void RelayTest()
190190
server.StartServer();
191191
//Task.Run(async () => { while (true) { await Task.Delay(10000); server.GetTcpStatistics(out var generalStats, out _); Console.WriteLine(generalStats.ToString()); } });
192192
var clients = new List<RelayClient>();
193-
int numclients = 20;
193+
int numclients = 2;
194194
var pending = new Task[numclients];
195195
// Parallel.For(0, numclients, (i) =>
196196
for (int i = 0; i < numclients; i++)
197197

198198
{
199199
var client = new RelayClient(cert);
200+
client.MaxUdpPackageSize = 2000;
200201
client.OnMessageReceived += (reply) => ClientMsgReceived(client, reply);
201202
client.OnUdpMessageReceived += (reply) => ClientUdpReceived(client, reply);
202203
//client.OnPeerRegistered += (id) => { /*if (client.sessionId.CompareTo(id) > 0)*/ client.RequestHolePunchAsync(id, 10000, false); };
@@ -219,17 +220,17 @@ private static void RelayTest()
219220
List<Task<bool>> pndg = new List<Task<bool>>();
220221
foreach (var client in clients)
221222
{
222-
if (client.sessionId == Guid.Empty)
223+
if (client.SessionId == Guid.Empty)
223224
throw new Exception();
224225
// Console.WriteLine("--- -- - | "+client.sessionId+" count: " + client.Peers.Count);
225226
foreach (var peer in client.Peers)
226227
{
227-
if (client.sessionId.CompareTo(peer.Key) > 0)
228+
if (client.SessionId.CompareTo(peer.Key) > 0)
228229
{
229230
if (peer.Key == Guid.Empty)
230231
throw new Exception();
231232

232-
//var a = client.RequestHolePunchAsync(peer.Key, 10000, false);
233+
var a = client.RequestHolePunchAsync(peer.Key, 10000, false);
233234
//pndg.Add(a);
234235
//client.TestHP(peer.Key, 10000, false);
235236
// Console.WriteLine(peer.Key+" cnt=> "+ ++cc);
@@ -248,7 +249,7 @@ private static void RelayTest()
248249
var testMessage = new MessageEnvelope()
249250
{
250251
Header = "Test",
251-
Payload = new byte[12600]
252+
Payload = new byte[126000]
252253
};
253254
for (int i = 0; i < testMessage.PayloadCount; i++)
254255
{

Json/JsonNetwork/JsonNetwork.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
66
<PackageId>Json.Network.Library</PackageId>
77
<Title>Json Network Library</Title>
8-
<Version>1.0.1</Version>
8+
<Version>1.0.2</Version>
99
<Authors>ReferenceType</Authors>
1010
<Description>Message passing and P2P network library using System.Text.Json</Description>
1111
<Copyright>Apache-2.0</Copyright>

MessagePack/MessagePackNetwork/MessagePackNetwork.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
66
<PackageId>MessagePack.Network.Library</PackageId>
77
<Title>MessagePack Network Library</Title>
8-
<Version>1.0.1</Version>
8+
<Version>1.0.2</Version>
99
<Authors>ReferenceType</Authors>
1010
<Description>Message passing and P2P network library using MessagePack Serialization</Description>
1111
<Copyright>Apache-2.0</Copyright>

NetSerializer/NetSerializerNetwork/NetSerializerNetwork.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
66
<PackageId>NetSerializer.Network.Library</PackageId>
77
<Title>NetSerializer Network Library</Title>
8-
<Version>1.0.1</Version>
8+
<Version>1.0.2</Version>
99
<Description>Message passing and P2P network library using .NetSerializer</Description>
1010
<Copyright>Apache-2.0</Copyright>
1111
<RepositoryUrl>https://github.com/ReferenceType/StandardNetworkLibrary</RepositoryUrl>

NetworkLibrary/MessageProtocol/Serialization/PrimitiveEncoder.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,16 @@ public static void WriteFixedUint16(PooledMemoryStream stream, ushort value)
143143
stream.WriteUshort(value);
144144
}
145145

146+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
147+
public unsafe static void WriteFixedUint16(byte[]buffer, int offset, ushort value)
148+
{
149+
if(buffer.Length-offset < 2)
150+
throw new InvalidDataException("Buffer does not have enough space");
151+
152+
fixed (byte* b = &buffer[offset])
153+
*(short*)b = (short)value;
154+
}
155+
146156
[MethodImpl(MethodImplOptions.AggressiveInlining)]
147157
public static ushort ReadUInt16(PooledMemoryStream stream)
148158
{

NetworkLibrary/NetworkLibrary.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
<RepositoryUrl>https://github.com/ReferenceType/StandardNetworkLibrary</RepositoryUrl>
1313
<Authors>RefrenceType</Authors>
1414
<Copyright>Apache 2.0</Copyright>
15-
<Version>2.0.1</Version>
15+
<Version>2.0.2</Version>
1616
<AssemblyVersion>2.0.1</AssemblyVersion>
1717
<FileVersion>2.0.1</FileVersion>
1818
<PackageReleaseNotes>Relay and room server are no longer generic but directly implemented on NetworkLibrary.P2P.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Net;
4+
using System.Text;
5+
6+
namespace NetworkLibrary
7+
{
8+
internal class IPUtils
9+
{
10+
//10.0.0.0 - 10.255.255.255
11+
//172.16.0.0 - 172.31.255.255
12+
//192.168.0.0 - 192.168.255.255
13+
public static bool IsPrivate(byte[] ipBytes)
14+
{
15+
if (ipBytes[0]== 192 && ipBytes[1] == 168)
16+
{
17+
return true;
18+
}
19+
else if (ipBytes[0] == 10)
20+
{
21+
return true;
22+
}
23+
else if (ipBytes[0] ==172 && (ipBytes[1]>15 && ipBytes[1] < 31))
24+
{
25+
return true;
26+
}
27+
else { return false;}
28+
}
29+
30+
public static bool IsLoopback(byte[] ipBtyes)
31+
{
32+
var addr = new IPAddress(ipBtyes);
33+
if (IPAddress.IsLoopback(addr))
34+
{
35+
return true;
36+
}
37+
return false;
38+
}
39+
}
40+
}

NetworkLibrary/P2P/Components/Modules/ClientUdpModule.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ namespace NetworkLibrary.P2P.Components.Modules
1818
private GenericMessageSerializer<S> serialiser = new GenericMessageSerializer<S>();
1919

2020
public ClientUdpModule(int port) : base(port) { }
21-
21+
public int MaxUdpPackageSize = 62400;
2222
private static void GetTLSStream()
2323
{
2424
if (TLSSerialisationStream == null)
@@ -39,7 +39,7 @@ public bool TrySendAsync(IPEndPoint endpoint, MessageEnvelope message, out Poole
3939

4040
serialiser.EnvelopeMessageWithBytes(TLSSerialisationStream,
4141
message, message.Payload, message.PayloadOffset, message.PayloadCount);
42-
if (TLSSerialisationStream.Position32 > 64500)
42+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
4343
{
4444
streamWithLargeMessage = TLSSerialisationStream;
4545
return false;
@@ -58,7 +58,7 @@ public bool TrySendAsync<T>(IPEndPoint endpoint, MessageEnvelope message, T inne
5858
serialiser.EnvelopeMessageWithInnerMessage(TLSSerialisationStream,
5959
message, innerMessage);
6060

61-
if (TLSSerialisationStream.Position32 > 64500)
61+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
6262
{
6363
excessStream = TLSSerialisationStream;
6464
return false;
@@ -77,7 +77,7 @@ public bool TrySendAsync(IPEndPoint endpoint, MessageEnvelope message, Action<Po
7777
message, SerializationCallback);
7878

7979
excessStream = null;
80-
if (TLSSerialisationStream.Position32 > 64500)
80+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
8181
{
8282
excessStream = TLSSerialisationStream;
8383
return false;
@@ -98,7 +98,7 @@ public bool TrySendAsync(IPEndPoint endpoint, MessageEnvelope message, Concurren
9898
serialiser.EnvelopeMessageWithBytes(TLSSerialisationStream,
9999
message, message.Payload, message.PayloadOffset, message.PayloadCount);
100100

101-
if (TLSSerialisationStream.Position32 > 64500)
101+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
102102
{
103103
largeMessageStream = TLSSerialisationStream;
104104
return false;
@@ -120,7 +120,7 @@ public bool TrySendAsync(IPEndPoint endpoint, MessageEnvelope message, Action<Po
120120
message, SerializationCallback);
121121

122122
excessStream = null;
123-
if (TLSSerialisationStream.Position32 > 64500)
123+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
124124
{
125125
excessStream = TLSSerialisationStream;
126126
return false;
@@ -142,7 +142,7 @@ public bool TrySendAsync<T>(IPEndPoint endpoint, MessageEnvelope message, T inne
142142

143143
serialiser.EnvelopeMessageWithInnerMessage(TLSSerialisationStream,
144144
message, innerMessage);
145-
if (TLSSerialisationStream.Position32 > 64500)
145+
if (TLSSerialisationStream.Position32 > MaxUdpPackageSize)
146146
{
147147
excessStream = TLSSerialisationStream;
148148
return false;

NetworkLibrary/P2P/Components/Modules/ReliableUdp.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public void Send(in Segment first, in Segment second)
101101
sender.ProcessBytesToSend(first, second);
102102
}
103103

104-
internal void Close()
104+
internal void Release()
105105
{
106106
OnReceived = null;
107107
OnSend = null;

NetworkLibrary/P2P/Components/StateManagemet/Client/ClientHolepunchState.cs

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
using NetworkLibrary.P2P.Components.HolePunch;
33
using System;
44
using System.Collections.Generic;
5+
using System.Linq;
56
using System.Net;
67
using System.Threading;
78
using System.Threading.Tasks;
9+
using System.Transactions;
810

911
namespace NetworkLibrary.P2P.Components.StateManagemet.Client
1012
{
@@ -16,6 +18,7 @@ internal class ClientHolepunchState : IState
1618
internal Guid destinationId;
1719
internal IPEndPoint succesfulEpToReceive;
1820
internal IPEndPoint succesfullEpToSend;
21+
internal IPEndPoint relayServerEndpoint;
1922
internal Action Success;
2023
internal Action<byte[], List<EndpointData>> KeyReceived;
2124
internal EndpointTransferMessage targetEndpoints;
@@ -29,11 +32,12 @@ internal class ClientHolepunchState : IState
2932
private StateManager client;
3033
private int totalPunchRoutines = 0;
3134
private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
32-
public ClientHolepunchState(Guid destinationId, Guid stateId, StateManager client)
35+
public ClientHolepunchState(Guid destinationId, Guid stateId, StateManager client, IPEndPoint relayServerEndpoint)
3336
{
3437
this.destinationId = destinationId;
3538
StateId = stateId;
3639
this.client = client;
40+
this.relayServerEndpoint = relayServerEndpoint;
3741
}
3842
// A asks B
3943
public void Initiate()
@@ -46,7 +50,7 @@ public void InitiateByRemote(MessageEnvelope message)
4650
HandleEndpointMessage(message);
4751
}
4852
// get remote ep then punch
49-
private void RetrieveRemoteEndpoint(Guid destinatioinId)
53+
private void RetrieveRemoteEndpoint(Guid destinationId)
5054
{
5155
var message = new MessageEnvelope
5256
{
@@ -56,28 +60,59 @@ private void RetrieveRemoteEndpoint(Guid destinatioinId)
5660
};
5761
if (encypted)
5862
message.KeyValuePairs = new Dictionary<string, string>() { { "Encrypted", null } };
59-
client.SendAsyncMessage(destinatioinId, message);
63+
client.SendAsyncMessage(destinationId, message);
6064
// reply will be handled on HandleEndpointMessage
6165
}
6266

6367
private void HandleEndpointMessage(MessageEnvelope message)
6468
{
6569
targetEndpoints = KnownTypeSerializer.DeserializeEndpointTransferMessage(message.Payload, message.PayloadOffset);
66-
cryptoKey = targetEndpoints.IpRemote;
70+
71+
// the remote ip on relay is local means relay server and remote client is in same local network
72+
var ipToVerify = targetEndpoints.LocalEndpoints.Last().Ip;
73+
if (IPUtils.IsLoopback(ipToVerify) || IPUtils.IsPrivate(ipToVerify))
74+
{
75+
// (localhost client + relay) vs remote client
76+
//if im not also local, i should try the internet address of the relay.
77+
var relayIp = relayServerEndpoint.Address.GetAddressBytes();
78+
if (!IPUtils.IsLoopback(relayIp) && !IPUtils.IsPrivate(relayIp))
79+
targetEndpoints.LocalEndpoints.Add(new EndpointData(new IPEndPoint(relayServerEndpoint.Address, targetEndpoints.LocalEndpoints[0].Port)));
80+
}
81+
82+
// Here we need to remove loopback because i might send messages to myself if we share the same port..
83+
List<EndpointData> toRemove = new List<EndpointData>();
84+
foreach (var endpoint in targetEndpoints.LocalEndpoints)
85+
{
86+
if (IPUtils.IsLoopback(endpoint.Ip))
87+
{
88+
toRemove.Add(endpoint);
89+
}
90+
91+
}
92+
foreach (var item in toRemove)
93+
{
94+
targetEndpoints.LocalEndpoints.Remove(item);
95+
}
96+
97+
cryptoKey = targetEndpoints.IpRemote;// yea, didnt wanna change the type
6798
KeyReceived?.Invoke(cryptoKey, targetEndpoints.LocalEndpoints);
6899
if (cryptoKey != null)
69100
{
70101
aesAlgorithm = new ConcurrentAesAlgorithm(cryptoKey, cryptoKey);
71102
}
103+
72104
var count = targetEndpoints.LocalEndpoints.Count;
73105
Interlocked.Exchange(ref totalPunchRoutines, count);
74106
for (int i = 0; i < count; i++)
75107
{
108+
var Ip = targetEndpoints.LocalEndpoints[i].Ip;
76109
var ep = targetEndpoints.LocalEndpoints[i].ToIpEndpoint();
77110

78-
// last one is remote end point, we need to try locals first.
79-
if (i == count - 1)
111+
// first handle the local ips, start remote later, because if we are on local why go through internet..
112+
if (!IPUtils.IsPrivate(Ip))
113+
{
80114
PunchRoutine(ep, delay: true);
115+
}
81116
else
82117
PunchRoutine(ep);
83118
}
@@ -95,7 +130,7 @@ private async void PunchRoutine(IPEndPoint ep, bool delay = false)
95130

96131
if (delay)
97132
{
98-
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
133+
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
99134
}
100135
// Console.WriteLine("Punching towards: " + ep.ToString());
101136

@@ -131,7 +166,7 @@ private async void PunchRoutine(IPEndPoint ep, bool delay = false)
131166
// inside of this message i must put the endpoint i shot at
132167
public void HandleMessage(IPEndPoint remoteEndpoint, MessageEnvelope message)
133168
{
134-
169+
// here i would like to receive all, then rank the ips select nearest.
135170
if (Interlocked.CompareExchange(ref succesfulEpToReceive, remoteEndpoint, null) == null)
136171
{
137172
//Console.WriteLine("Received Sucess: " + remoteEndpoint.ToString());
@@ -168,9 +203,10 @@ public void HandleMessage(MessageEnvelope message)
168203
if (Interlocked.Exchange(ref stop, 1) == 0)
169204
{
170205
cancellationTokenSource.Cancel();
171-
Consensus();
172206
// get the sucessfull ep
173207
succesfullEpToSend = KnownTypeSerializer.DeserializeEndpointData(message.Payload, message.PayloadOffset).ToIpEndpoint();
208+
Consensus();
209+
174210
}
175211
}
176212
else if (message.Header == Constants.HolpunchMessagesSent)
@@ -220,7 +256,7 @@ public void Release(bool isCompletedSuccessfully)
220256
{
221257
if (Interlocked.CompareExchange(ref isReleased, 1, 0) == 0)
222258
{
223-
if (isCompletedSuccessfully)
259+
if (isCompletedSuccessfully && succesfullEpToSend != null && succesfulEpToReceive != null)
224260
currentStatus = StateStatus.Completed;
225261
else
226262
currentStatus = StateStatus.Failed;

0 commit comments

Comments
 (0)