-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelayServer.cs
More file actions
81 lines (69 loc) · 2.28 KB
/
RelayServer.cs
File metadata and controls
81 lines (69 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Text;
using NLog;
namespace Relay;
public class RelayServer(ushort port, string gameProtocolVersion)
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public readonly ConcurrentDictionary<IPEndPoint, byte> Players = new();
public readonly ConcurrentDictionary<string, byte> AllowFrom = new();
private readonly UdpClient _udpClient = new(port);
public ushort Port { get; } = port;
public string GameProtocolVersion { get; } = gameProtocolVersion;
private readonly CancellationTokenSource _cts = new();
public void Start()
{
Logger.Debug("Starting RelayServer on port: " + port);
_ = RunAsync();
}
public void Stop()
{
_cts.Cancel();
_udpClient.Close();
}
private async Task RunAsync()
{
while (true)
{
try
{
var result = await _udpClient.ReceiveAsync();
_ = ProcessPacketAsync(result);
}
catch (Exception)
{
break;
}
}
}
private async Task ProcessPacketAsync(UdpReceiveResult result)
{
string remoteIp = result.RemoteEndPoint.Address.ToString();
if (!Players.ContainsKey(result.RemoteEndPoint))
{
if (AllowFrom.TryRemove(remoteIp, out _))
{
Players.TryAdd(result.RemoteEndPoint, 0);
}
else
{
Logger.Warn($"Blocked udp traffic from unknown address: {result.RemoteEndPoint.Address}");
return;
}
}
if (Program.ShowTraffic) Logger.Debug("Received: " + ByteArrayToString(result.Buffer) + " from:" + result.RemoteEndPoint);
var sendTasks = Players.Keys
.Where(ep => !ep.Equals(result.RemoteEndPoint))
.Select(ep => _udpClient.SendAsync(result.Buffer, result.Buffer.Length, ep));
await Task.WhenAll(sendTasks);
}
private static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}