From 863156a0dc12559f4c66a503b274ccdfefe307f6 Mon Sep 17 00:00:00 2001 From: cxxpxr <60411087+cxxpxr@users.noreply.github.com> Date: Thu, 6 May 2021 10:06:43 -0400 Subject: [PATCH] cleanup --- .../LRM/Compression.cs | 6 +- .../LRM/Endpoint.cs | 4 +- .../LRM/Program/Program.cs | 20 ++- .../LRM/Program/ProgramNATHandler.cs | 6 +- .../LRM/RelayHandler/RelayHandler.cs | 165 +++++++++--------- .../RelayHandler/RelayHandlerRoomMethods.cs | 108 ++++++------ .../LRM/RelayHandler/RelayHandlerVariables.cs | 15 +- 7 files changed, 168 insertions(+), 156 deletions(-) diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Compression.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Compression.cs index 5eac1a5..4b46f5e 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Compression.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Compression.cs @@ -35,11 +35,11 @@ namespace LightReflectiveMirror.Compression /// /// Decompresses the string. /// - /// The compressed text. + /// The compressed text. /// - public static string Decompress(this string compressedText) + public static string Decompress(this string text) { - byte[] gZipBuffer = Convert.FromBase64String(compressedText); + byte[] gZipBuffer = Convert.FromBase64String(text); using (var memoryStream = new MemoryStream()) { int dataLength = BitConverter.ToInt32(gZipBuffer, 0); diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Endpoint.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Endpoint.cs index 36a29c0..995a1bf 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Endpoint.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Endpoint.cs @@ -29,7 +29,7 @@ namespace LightReflectiveMirror.Endpoints private static List _rooms { get => Program.instance.GetRooms().Where(x => x.isPublic).ToList(); } - private RelayStats _stats { get => new RelayStats + private RelayStats _stats { get => new() { ConnectedClients = Program.instance.GetConnections(), RoomCount = Program.instance.GetRooms().Count, @@ -43,7 +43,7 @@ namespace LightReflectiveMirror.Endpoints _cachedCompressedServerList = _cachedServerList.Compress(); if (Program.conf.UseLoadBalancer) - Program.instance.UpdateLoadbalancerServers(); + Program.instance.UpdateLoadBalancerServers(); } [RestRoute("Get", "/api/stats")] diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/Program.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/Program.cs index e6f028b..eccf1cf 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/Program.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/Program.cs @@ -120,11 +120,12 @@ namespace LightReflectiveMirror } } - public async void UpdateLoadbalancerServers() + public async void UpdateLoadBalancerServers() { try { - using(WebClient wc = new WebClient()){ + using(WebClient wc = new()) + { wc.Headers.Add("Authorization", conf.LoadBalancerAuthKey); await wc.DownloadStringTaskAsync($"http://{conf.LoadBalancerAddress}:{conf.LoadBalancerPort}/api/roomsupdated"); } @@ -146,11 +147,7 @@ namespace LightReflectiveMirror string gamePort = conf.TransportPort.ToString(); HttpWebRequest authReq = (HttpWebRequest)WebRequest.Create(uri); - authReq.Headers.Add("Authorization", conf.LoadBalancerAuthKey); - authReq.Headers.Add("x-EndpointPort", endpointPort); - authReq.Headers.Add("x-GamePort", gamePort); - authReq.Headers.Add("x-PIP", publicIP); // Public IP - authReq.Headers.Add("x-Region", ((int)conf.LoadBalancerRegion).ToString()); + ConfigureHeaders(endpointPort, gamePort, authReq); var res = await authReq.GetResponseAsync(); @@ -163,5 +160,14 @@ namespace LightReflectiveMirror return false; } } + + private static void ConfigureHeaders(string endpointPort, string gamePort, HttpWebRequest authReq) + { + authReq.Headers.Add("Authorization", conf.LoadBalancerAuthKey); + authReq.Headers.Add("x-EndpointPort", endpointPort); + authReq.Headers.Add("x-GamePort", gamePort); + authReq.Headers.Add("x-PIP", publicIP); // Public IP + authReq.Headers.Add("x-Region", ((int)conf.LoadBalancerRegion).ToString()); + } } } diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/ProgramNATHandler.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/ProgramNATHandler.cs index 968cc15..ba7f883 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/ProgramNATHandler.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Program/ProgramNATHandler.cs @@ -14,7 +14,7 @@ namespace LightReflectiveMirror var serverResponse = new byte[1] { 1 }; byte[] readData; - bool isConnectionEstablishment; + bool isConnectionEstablished; int pos; string connectionID; @@ -24,9 +24,9 @@ namespace LightReflectiveMirror pos = 0; try { - isConnectionEstablishment = readData.ReadBool(ref pos); + isConnectionEstablished = readData.ReadBool(ref pos); - if (isConnectionEstablishment) + if (isConnectionEstablished) { connectionID = readData.ReadString(ref pos); diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandler.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandler.cs index 7b6f666..5898051 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandler.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandler.cs @@ -1,13 +1,12 @@ using System; using System.Buffers; using System.Linq; -using System.Net; namespace LightReflectiveMirror { public partial class RelayHandler { - + // constructor for new relay handler public RelayHandler(int maxPacketSize) { this._maxPacketSize = maxPacketSize; @@ -15,86 +14,38 @@ namespace LightReflectiveMirror } /// - /// This is called when a client wants to send data to another player. + /// Checks if a server id already is in use. /// - /// The ID of the client who is sending the data - /// The binary data the client is sending - /// The channel the client is sending this data on - /// Who to relay the data to - void ProcessData(int clientId, byte[] clientData, int channel, int sendTo = -1) - { - Room room = _cachedClientRooms[clientId]; + /// The ID to check for + /// + private bool DoesServerIdExist(string id) => _cachedRooms.ContainsKey(id); - if(room != null) + private string GenerateRoomID() + { + const int LENGTH = 5; + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + var randomID = ""; + var random = new Random(); + + do { - if(room.hostId == clientId) - { - if (room.clients.Contains(sendTo)) - { - int pos = 0; - byte[] sendBuffer = _sendBuffers.Rent(_maxPacketSize); - - sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetData); - sendBuffer.WriteBytes(ref pos, clientData); - - Program.transport.ServerSend(sendTo, channel, new ArraySegment(sendBuffer, 0, pos)); - _sendBuffers.Return(sendBuffer); - } - } - else - { - // We are not the host, so send the data to the host. - int pos = 0; - byte[] sendBuffer = _sendBuffers.Rent(_maxPacketSize); - - sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetData); - sendBuffer.WriteBytes(ref pos, clientData); - sendBuffer.WriteInt(ref pos, clientId); - - Program.transport.ServerSend(room.hostId, channel, new ArraySegment(sendBuffer, 0, pos)); - _sendBuffers.Return(sendBuffer); - } + randomID = new string(Enumerable.Repeat(chars, LENGTH) + .Select(s => s[random.Next(s.Length)]).ToArray()); } - } + while (DoesServerIdExist(randomID)); - - /// - /// Called when a client wants to request their own ID. - /// - /// The client requesting their ID - void SendClientID(int clientId) - { - int pos = 0; - byte[] sendBuffer = _sendBuffers.Rent(5); - - sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetID); - sendBuffer.WriteInt(ref pos, clientId); - - Program.transport.ServerSend(clientId, 0, new ArraySegment(sendBuffer, 0, pos)); - _sendBuffers.Return(sendBuffer); + return randomID; } /// /// Generates a random server ID. /// /// - string GetRandomServerID() + private string GetRandomServerID() { if (!Program.conf.UseLoadBalancer) { - const int LENGTH = 5; - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - var randomID = ""; - - do - { - var random = new System.Random(); - randomID = new string(Enumerable.Repeat(chars, LENGTH) - .Select(s => s[random.Next(s.Length)]).ToArray()); - } - while (DoesServerIdExist(randomID)); - - return randomID; + return GenerateRoomID(); } else { @@ -107,20 +58,72 @@ namespace LightReflectiveMirror } /// - /// Checks if a server id already is in use. + /// This is called when a client wants to send data to another player. /// - /// The ID to check for - /// - bool DoesServerIdExist(string id) + /// The ID of the client who is sending the data + /// The binary data the client is sending + /// The channel the client is sending this data on + /// Who to relay the data to + private void ProcessData(int clientId, byte[] clientData, int channel, int sendTo = -1) { - return _cachedRooms.ContainsKey(id); + Room room = _cachedClientRooms[clientId]; + + if (room != null) + { + if (room.hostId == clientId) + { + if (room.clients.Contains(sendTo)) + { + SendData(clientData, channel, sendTo); + } + } + else + { + SendDataToRoomHost(clientId, clientData, channel, room); + } + } + } + + private void SendData(byte[] clientData, int channel, int sendTo) + { + int pos = 0; + byte[] sendBuffer = _sendBuffers.Rent(_maxPacketSize); + + sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetData); + sendBuffer.WriteBytes(ref pos, clientData); + + Program.transport.ServerSend(sendTo, channel, new ArraySegment(sendBuffer, 0, pos)); + _sendBuffers.Return(sendBuffer); + } + + private void SendDataToRoomHost(int clientId, byte[] clientData, int channel, Room room) + { + // We are not the host, so send the data to the host. + int pos = 0; + byte[] sendBuffer = _sendBuffers.Rent(_maxPacketSize); + + sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetData); + sendBuffer.WriteBytes(ref pos, clientData); + sendBuffer.WriteInt(ref pos, clientId); + + Program.transport.ServerSend(room.hostId, channel, new ArraySegment(sendBuffer, 0, pos)); + _sendBuffers.Return(sendBuffer); + } + + /// + /// Called when a client wants to request their own ID. + /// + /// The client requesting their ID + private void SendClientID(int clientId) + { + int pos = 0; + byte[] sendBuffer = _sendBuffers.Rent(5); + + sendBuffer.WriteByte(ref pos, (byte)OpCodes.GetID); + sendBuffer.WriteInt(ref pos, clientId); + + Program.transport.ServerSend(clientId, 0, new ArraySegment(sendBuffer, 0, pos)); + _sendBuffers.Return(sendBuffer); } } - - public enum OpCodes - { - Default = 0, RequestID = 1, JoinServer = 2, SendData = 3, GetID = 4, ServerJoined = 5, GetData = 6, CreateRoom = 7, ServerLeft = 8, PlayerDisconnected = 9, RoomCreated = 10, - LeaveRoom = 11, KickPlayer = 12, AuthenticationRequest = 13, AuthenticationResponse = 14, Authenticated = 17, UpdateRoomData = 18, ServerConnectionData = 19, RequestNATConnection = 20, - DirectConnectIP = 21 - } -} +} \ No newline at end of file diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerRoomMethods.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerRoomMethods.cs index 31cd082..93f8b5d 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerRoomMethods.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerRoomMethods.cs @@ -7,6 +7,55 @@ namespace LightReflectiveMirror { public partial class RelayHandler { + /// + /// Creates a room on the LRM node. + /// + /// The client requesting to create a room + /// The maximum amount of players for this room + /// The name for the server + /// Weather or not the server should show up on the server list + /// Extra data the host can include + /// Weather or not, the host is capable of doing direct connections + /// The hosts local IP + /// Weather or not, the host is supporting NAT Punch + /// The port of the direct connect transport on the host + private void CreateRoom(int clientId, int maxPlayers, string serverName, bool isPublic, string serverData, bool useDirectConnect, string hostLocalIP, bool useNatPunch, int port) + { + LeaveRoom(clientId); + Program.instance.NATConnections.TryGetValue(clientId, out IPEndPoint hostIP); + + Room room = new() + { + hostId = clientId, + maxPlayers = maxPlayers, + serverName = serverName, + isPublic = isPublic, + serverData = serverData, + clients = new List(), + serverId = GetRandomServerID(), + hostIP = hostIP, + hostLocalIP = hostLocalIP, + supportsDirectConnect = hostIP != null && useDirectConnect, + port = port, + useNATPunch = useNatPunch, + relayInfo = new RelayAddress { address = Program.publicIP, port = Program.conf.TransportPort, endpointPort = Program.conf.EndpointPort } + }; + + rooms.Add(room); + _cachedClientRooms.Add(clientId, room); + _cachedRooms.Add(room.serverId, room); + + int pos = 0; + byte[] sendBuffer = _sendBuffers.Rent(5); + + sendBuffer.WriteByte(ref pos, (byte)OpCodes.RoomCreated); + sendBuffer.WriteString(ref pos, room.serverId); + + Program.transport.ServerSend(clientId, 0, new ArraySegment(sendBuffer, 0, pos)); + _sendBuffers.Return(sendBuffer); + + Endpoint.RoomsModified(); + } /// /// Attempts to join a room for a client. @@ -15,7 +64,7 @@ namespace LightReflectiveMirror /// The server ID of the room /// If the client is capable of a direct connection /// The local IP of the client joining - void JoinRoom(int clientId, string serverId, bool canDirectConnect, string localIP) + private void JoinRoom(int clientId, string serverId, bool canDirectConnect, string localIP) { LeaveRoom(clientId); @@ -64,7 +113,6 @@ namespace LightReflectiveMirror } else { - sendJoinBuffer.WriteByte(ref sendJoinPos, (byte)OpCodes.ServerJoined); sendJoinBuffer.WriteInt(ref sendJoinPos, clientId); @@ -88,64 +136,12 @@ namespace LightReflectiveMirror _sendBuffers.Return(sendBuffer); } - /// - /// Creates a room on the LRM node. - /// - /// The client requesting to create a room - /// The maximum amount of players for this room - /// The name for the server - /// Weather or not the server should show up on the server list - /// Extra data the host can include - /// Weather or not, the host is capable of doing direct connections - /// The hosts local IP - /// Weather or not, the host is supporting NAT Punch - /// The port of the direct connect transport on the host - void CreateRoom(int clientId, int maxPlayers, string serverName, bool isPublic, string serverData, bool useDirectConnect, string hostLocalIP, bool useNatPunch, int port) - { - LeaveRoom(clientId); - Program.instance.NATConnections.TryGetValue(clientId, out IPEndPoint hostIP); - - Room room = new Room - { - hostId = clientId, - maxPlayers = maxPlayers, - serverName = serverName, - isPublic = isPublic, - serverData = serverData, - clients = new List(), - - relayInfo = new RelayAddress { address = Program.publicIP, port = Program.conf.TransportPort, endpointPort = Program.conf.EndpointPort }, - - serverId = GetRandomServerID(), - hostIP = hostIP, - hostLocalIP = hostLocalIP, - supportsDirectConnect = hostIP != null && useDirectConnect, - port = port, - useNATPunch = useNatPunch - }; - - rooms.Add(room); - _cachedClientRooms.Add(clientId, room); - _cachedRooms.Add(room.serverId, room); - - int pos = 0; - byte[] sendBuffer = _sendBuffers.Rent(5); - - sendBuffer.WriteByte(ref pos, (byte)OpCodes.RoomCreated); - sendBuffer.WriteString(ref pos, room.serverId); - - Program.transport.ServerSend(clientId, 0, new ArraySegment(sendBuffer, 0, pos)); - _sendBuffers.Return(sendBuffer); - - Endpoint.RoomsModified(); - } - /// /// Makes the client leave their room. /// /// The client of which to remove from their room /// The ID of the client who kicked the client. -1 if the client left on their own terms - void LeaveRoom(int clientId, int requiredHostId = -1) + private void LeaveRoom(int clientId, int requiredHostId = -1) { for (int i = 0; i < rooms.Count; i++) { @@ -191,4 +187,4 @@ namespace LightReflectiveMirror } } } -} +} \ No newline at end of file diff --git a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerVariables.cs b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerVariables.cs index c5fee9e..e7f3a17 100644 --- a/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerVariables.cs +++ b/ServerProject-DONT-IMPORT-INTO-UNITY/LRM/RelayHandler/RelayHandlerVariables.cs @@ -5,11 +5,18 @@ namespace LightReflectiveMirror { public partial class RelayHandler { - public List rooms = new List(); - private List _pendingAuthentication = new List(); + public List rooms = new(); + private List _pendingAuthentication = new(); private ArrayPool _sendBuffers; private int _maxPacketSize = 0; - private Dictionary _cachedClientRooms = new Dictionary(); - private Dictionary _cachedRooms = new Dictionary(); + private Dictionary _cachedClientRooms = new(); + private Dictionary _cachedRooms = new(); + } + + public enum OpCodes + { + Default = 0, RequestID = 1, JoinServer = 2, SendData = 3, GetID = 4, ServerJoined = 5, GetData = 6, CreateRoom = 7, ServerLeft = 8, PlayerDisconnected = 9, RoomCreated = 10, + LeaveRoom = 11, KickPlayer = 12, AuthenticationRequest = 13, AuthenticationResponse = 14, Authenticated = 17, UpdateRoomData = 18, ServerConnectionData = 19, RequestNATConnection = 20, + DirectConnectIP = 21 } }