Skip to content
This repository was archived by the owner on Sep 5, 2022. It is now read-only.

Commit 92f0c7c

Browse files
committed
Cleanup
switched to use static webclient and refactored existing code.
1 parent 011f562 commit 92f0c7c

File tree

6 files changed

+191
-155
lines changed

6 files changed

+191
-155
lines changed

ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Config.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
namespace LightReflectiveMirror
66
{
7-
class Config
7+
public class Config
88
{
99
//========================
1010
// Required Settings

ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/Program.cs

Lines changed: 15 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,14 @@ namespace LightReflectiveMirror
1616
partial class Program
1717
{
1818
public static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult();
19-
public List<Room> GetRooms() => _relay.rooms;
2019

2120
public async Task MainAsync()
2221
{
2322
WriteTitle();
2423
instance = this;
2524
_startupTime = DateTime.Now;
26-
using (WebClient wc = new WebClient())
27-
{
28-
try
29-
{
30-
publicIP = wc.DownloadString("http://ipv4.icanhazip.com").Replace("\\r", "").Replace("\\n", "").Trim();
31-
}
32-
catch {
33-
WriteLogMessage("Failed to reach public IP endpoint! Using loopback address.", ConsoleColor.Yellow);
34-
publicIP = "127.0.0.1";
35-
}
36-
}
25+
26+
GetPublicIP();
3727

3828
if (!File.Exists(CONFIG_PATH))
3929
{
@@ -46,22 +36,7 @@ public async Task MainAsync()
4636
{
4737
conf = JsonConvert.DeserializeObject<Config>(File.ReadAllText(CONFIG_PATH));
4838

49-
// Docker variables.
50-
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_ENDPOINT_PORT"), out ushort endpointPort))
51-
conf.EndpointPort = endpointPort;
52-
53-
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_TRANSPORT_PORT"), out ushort transportPort))
54-
conf.TransportPort = transportPort;
55-
56-
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_PUNCHER_PORT"), out ushort puncherPort))
57-
conf.NATPunchtroughPort = puncherPort;
58-
59-
string LBAuthKey = Environment.GetEnvironmentVariable("LRM_LB_AUTHKEY");
60-
if (!string.IsNullOrWhiteSpace(LBAuthKey))
61-
{
62-
conf.LoadBalancerAuthKey = LBAuthKey;
63-
WriteLogMessage("\nLoaded LB auth key from environment variable\n", ConsoleColor.Green);
64-
}
39+
ConfigureDocker();
6540

6641
WriteLogMessage("Loading Assembly... ", ConsoleColor.White, true);
6742
try
@@ -75,109 +50,13 @@ public async Task MainAsync()
7550

7651
if (transport != null)
7752
{
78-
var transportClass = asm.GetType(conf.TransportClass);
79-
WriteLogMessage("OK", ConsoleColor.Green);
80-
81-
WriteLogMessage("\nLoading Transport Methods... ", ConsoleColor.White, true);
82-
CheckMethods(transportClass);
83-
WriteLogMessage("OK", ConsoleColor.Green);
84-
85-
WriteLogMessage("\nInvoking Transport Methods...");
86-
87-
if (_awakeMethod != null)
88-
_awakeMethod.Invoke(transport, null);
89-
90-
if (_startMethod != null)
91-
_startMethod.Invoke(transport, null);
92-
93-
WriteLogMessage("\nStarting Transport... ", ConsoleColor.White, true);
94-
95-
transport.OnServerError = (clientID, error) =>
96-
{
97-
WriteLogMessage($"Transport Error, Client: {clientID}, Error: {error}", ConsoleColor.Red);
98-
};
99-
100-
transport.OnServerConnected = (clientID) =>
101-
{
102-
WriteLogMessage($"Transport Connected, Client: {clientID}", ConsoleColor.Cyan);
103-
_currentConnections.Add(clientID);
104-
_relay.ClientConnected(clientID);
105-
106-
if (conf.EnableNATPunchtroughServer)
107-
{
108-
string natID = Guid.NewGuid().ToString();
109-
_pendingNATPunches.Add(clientID, natID);
110-
_NATRequestPosition = 0;
111-
_NATRequest.WriteByte(ref _NATRequestPosition, (byte)OpCodes.RequestNATConnection);
112-
_NATRequest.WriteString(ref _NATRequestPosition, natID);
113-
_NATRequest.WriteInt(ref _NATRequestPosition, conf.NATPunchtroughPort);
114-
transport.ServerSend(clientID, 0, new ArraySegment<byte>(_NATRequest, 0, _NATRequestPosition));
115-
}
116-
};
117-
118-
_relay = new RelayHandler(transport.GetMaxPacketSize(0));
119-
120-
transport.OnServerDataReceived = _relay.HandleMessage;
121-
transport.OnServerDisconnected = (clientID) =>
122-
{
123-
_currentConnections.Remove(clientID);
124-
_relay.HandleDisconnect(clientID);
125-
126-
if (NATConnections.ContainsKey(clientID))
127-
NATConnections.Remove(clientID);
128-
129-
if (_pendingNATPunches.TryGetByFirst(clientID, out _))
130-
_pendingNATPunches.Remove(clientID);
131-
};
132-
133-
transport.ServerStart(conf.TransportPort);
134-
135-
WriteLogMessage("OK", ConsoleColor.Green);
53+
ConfigureTransport(asm);
13654

13755
if (conf.UseEndpoint)
138-
{
139-
WriteLogMessage("\nStarting Endpoint Service... ", ConsoleColor.White, true);
140-
var endpointService = new EndpointServer();
141-
142-
if (endpointService.Start(conf.EndpointPort))
143-
{
144-
WriteLogMessage("OK", ConsoleColor.Green);
145-
Endpoint.RoomsModified();
146-
}
147-
else
148-
{
149-
WriteLogMessage("FAILED\nPlease run as administrator or check if port is in use.", ConsoleColor.DarkRed);
150-
}
151-
}
56+
ConfigureEndpoint();
15257

15358
if (conf.EnableNATPunchtroughServer)
154-
{
155-
WriteLogMessage("\nStarting NatPunchthrough Socket... ", ConsoleColor.White, true);
156-
157-
try
158-
{
159-
_punchServer = new UdpClient(conf.NATPunchtroughPort);
160-
161-
WriteLogMessage("OK\n", ConsoleColor.Green, true);
162-
163-
WriteLogMessage("\nStarting NatPunchthrough Thread... ", ConsoleColor.White, true);
164-
var natThread = new Thread(new ThreadStart(RunNATPunchLoop));
165-
166-
try
167-
{
168-
natThread.Start();
169-
}
170-
catch (Exception e)
171-
{
172-
WriteLogMessage("FAILED\n" + e, ConsoleColor.DarkRed);
173-
}
174-
}
175-
catch (Exception e)
176-
{
177-
WriteLogMessage("FAILED\nCheck if port is in use.", ConsoleColor.DarkRed, true);
178-
Console.WriteLine(e);
179-
}
180-
}
59+
ConfigurePunchthrough();
18160
}
18261
else
18362
{
@@ -197,6 +76,11 @@ public async Task MainAsync()
19776
await RegisterSelfToLoadBalancer();
19877
}
19978

79+
await HeartbeatLoop();
80+
}
81+
82+
private async Task HeartbeatLoop()
83+
{
20084
while (true)
20185
{
20286
try
@@ -209,7 +93,6 @@ public async Task MainAsync()
20993
WriteLogMessage("Error During Transport Update! " + e, ConsoleColor.Red);
21094
}
21195

212-
21396
_currentHeartbeatTimer++;
21497

21598
if (_currentHeartbeatTimer >= conf.UpdateHeartbeatInterval)
@@ -224,7 +107,9 @@ public async Task MainAsync()
224107
if (DateTime.Now > Endpoint.lastPing.AddSeconds(60))
225108
{
226109
// Dont await that on main thread. It would cause a lag spike for clients.
110+
#pragma warning disable CS4014
227111
RegisterSelfToLoadBalancer();
112+
#pragma warning restore CS4014
228113
}
229114
}
230115

@@ -239,11 +124,8 @@ public async void UpdateLoadbalancerServers()
239124
{
240125
try
241126
{
242-
using (WebClient wc = new())
243-
{
244-
wc.Headers.Add("Authorization", conf.LoadBalancerAuthKey);
245-
await wc.DownloadStringTaskAsync($"http://{conf.LoadBalancerAddress}:{conf.LoadBalancerPort}/api/roomsupdated");
246-
}
127+
webClient.Headers.Add("Authorization", conf.LoadBalancerAuthKey);
128+
await webClient.DownloadStringTaskAsync($"http://{conf.LoadBalancerAddress}:{conf.LoadBalancerPort}/api/roomsupdated");
247129
}
248130
catch { } // LLB might be down, ignore.
249131
}
@@ -279,13 +161,5 @@ private async Task<bool> RegisterSelfToLoadBalancer()
279161
return false;
280162
}
281163
}
282-
283-
void CheckMethods(Type type)
284-
{
285-
_awakeMethod = type.GetMethod("Awake", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
286-
_startMethod = type.GetMethod("Start", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
287-
_updateMethod = type.GetMethod("Update", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
288-
_lateUpdateMethod = type.GetMethod("LateUpdate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
289-
}
290164
}
291165
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
using LightReflectiveMirror.Endpoints;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Net.Sockets;
6+
using System.Reflection;
7+
using System.Text;
8+
using System.Threading;
9+
using System.Threading.Tasks;
10+
11+
namespace LightReflectiveMirror
12+
{
13+
public partial class Program
14+
{
15+
private void ConfigureTransport(Assembly asm)
16+
{
17+
var transportClass = asm.GetType(conf.TransportClass);
18+
WriteLogMessage("OK", ConsoleColor.Green);
19+
20+
WriteLogMessage("\nLoading Transport Methods... ", ConsoleColor.White, true);
21+
CheckMethods(transportClass);
22+
WriteLogMessage("OK", ConsoleColor.Green);
23+
24+
WriteLogMessage("\nInvoking Transport Methods...");
25+
26+
if (_awakeMethod != null)
27+
_awakeMethod.Invoke(transport, null);
28+
29+
if (_startMethod != null)
30+
_startMethod.Invoke(transport, null);
31+
32+
WriteLogMessage("\nStarting Transport... ", ConsoleColor.White, true);
33+
34+
transport.OnServerError = (clientID, error) =>
35+
{
36+
WriteLogMessage($"Transport Error, Client: {clientID}, Error: {error}", ConsoleColor.Red);
37+
};
38+
39+
transport.OnServerConnected = (clientID) =>
40+
{
41+
WriteLogMessage($"Transport Connected, Client: {clientID}", ConsoleColor.Cyan);
42+
_currentConnections.Add(clientID);
43+
_relay.ClientConnected(clientID);
44+
45+
if (conf.EnableNATPunchtroughServer)
46+
{
47+
string natID = Guid.NewGuid().ToString();
48+
_pendingNATPunches.Add(clientID, natID);
49+
_NATRequestPosition = 0;
50+
_NATRequest.WriteByte(ref _NATRequestPosition, (byte)OpCodes.RequestNATConnection);
51+
_NATRequest.WriteString(ref _NATRequestPosition, natID);
52+
_NATRequest.WriteInt(ref _NATRequestPosition, conf.NATPunchtroughPort);
53+
transport.ServerSend(clientID, 0, new ArraySegment<byte>(_NATRequest, 0, _NATRequestPosition));
54+
}
55+
};
56+
57+
_relay = new RelayHandler(transport.GetMaxPacketSize(0));
58+
59+
transport.OnServerDataReceived = _relay.HandleMessage;
60+
transport.OnServerDisconnected = (clientID) =>
61+
{
62+
_currentConnections.Remove(clientID);
63+
_relay.HandleDisconnect(clientID);
64+
65+
if (NATConnections.ContainsKey(clientID))
66+
NATConnections.Remove(clientID);
67+
68+
if (_pendingNATPunches.TryGetByFirst(clientID, out _))
69+
_pendingNATPunches.Remove(clientID);
70+
};
71+
72+
transport.ServerStart(conf.TransportPort);
73+
74+
WriteLogMessage("OK", ConsoleColor.Green);
75+
}
76+
77+
private static void ConfigureEndpoint()
78+
{
79+
WriteLogMessage("\nStarting Endpoint Service... ", ConsoleColor.White, true);
80+
var endpointService = new EndpointServer();
81+
82+
if (endpointService.Start(conf.EndpointPort))
83+
{
84+
WriteLogMessage("OK", ConsoleColor.Green);
85+
Endpoint.RoomsModified();
86+
}
87+
else
88+
{
89+
WriteLogMessage("FAILED\nPlease run as administrator or check if port is in use.", ConsoleColor.DarkRed);
90+
}
91+
}
92+
93+
private void ConfigurePunchthrough()
94+
{
95+
WriteLogMessage("\nStarting NatPunchthrough Socket... ", ConsoleColor.White, true);
96+
97+
try
98+
{
99+
_punchServer = new UdpClient(conf.NATPunchtroughPort);
100+
101+
WriteLogMessage("OK\n", ConsoleColor.Green, true);
102+
103+
WriteLogMessage("\nStarting NatPunchthrough Thread... ", ConsoleColor.White, true);
104+
var natThread = new Thread(new ThreadStart(RunNATPunchLoop));
105+
106+
try
107+
{
108+
natThread.Start();
109+
}
110+
catch (Exception e)
111+
{
112+
WriteLogMessage("FAILED\n" + e, ConsoleColor.DarkRed);
113+
}
114+
}
115+
catch (Exception e)
116+
{
117+
WriteLogMessage("FAILED\nCheck if port is in use.", ConsoleColor.DarkRed, true);
118+
Console.WriteLine(e);
119+
}
120+
}
121+
122+
private static void ConfigureDocker()
123+
{
124+
// Docker variables.
125+
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_ENDPOINT_PORT"), out ushort endpointPort))
126+
conf.EndpointPort = endpointPort;
127+
128+
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_TRANSPORT_PORT"), out ushort transportPort))
129+
conf.TransportPort = transportPort;
130+
131+
if (ushort.TryParse(Environment.GetEnvironmentVariable("LRM_PUNCHER_PORT"), out ushort puncherPort))
132+
conf.NATPunchtroughPort = puncherPort;
133+
134+
string LBAuthKey = Environment.GetEnvironmentVariable("LRM_LB_AUTHKEY");
135+
if (!string.IsNullOrWhiteSpace(LBAuthKey))
136+
{
137+
conf.LoadBalancerAuthKey = LBAuthKey;
138+
WriteLogMessage("\nLoaded LB auth key from environment variable\n", ConsoleColor.Green);
139+
}
140+
}
141+
142+
void CheckMethods(Type type)
143+
{
144+
_awakeMethod = type.GetMethod("Awake", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
145+
_startMethod = type.GetMethod("Start", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
146+
_updateMethod = type.GetMethod("Update", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
147+
_lateUpdateMethod = type.GetMethod("LateUpdate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
148+
}
149+
}
150+
}

0 commit comments

Comments
 (0)