This commit is contained in:
cxxpxr 2021-05-06 10:06:43 -04:00
parent 82f0399bb6
commit 863156a0dc
7 changed files with 168 additions and 156 deletions

View file

@ -35,11 +35,11 @@ namespace LightReflectiveMirror.Compression
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <param name="text">The compressed text.</param>
/// <returns></returns>
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);

View file

@ -29,7 +29,7 @@ namespace LightReflectiveMirror.Endpoints
private static List<Room> _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")]

View file

@ -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());
}
}
}

View file

@ -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);

View file

@ -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,80 +14,21 @@ namespace LightReflectiveMirror
}
/// <summary>
/// This is called when a client wants to send data to another player.
/// </summary>
/// <param name="clientId">The ID of the client who is sending the data</param>
/// <param name="clientData">The binary data the client is sending</param>
/// <param name="channel">The channel the client is sending this data on</param>
/// <param name="sendTo">Who to relay the data to</param>
void ProcessData(int clientId, byte[] clientData, int channel, int sendTo = -1)
{
Room room = _cachedClientRooms[clientId];
if(room != null)
{
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<byte>(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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
}
}
}
/// <summary>
/// Called when a client wants to request their own ID.
/// </summary>
/// <param name="clientId">The client requesting their ID</param>
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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
}
/// <summary>
/// Generates a random server ID.
/// Checks if a server id already is in use.
/// </summary>
/// <param name="id">The ID to check for</param>
/// <returns></returns>
string GetRandomServerID()
{
if (!Program.conf.UseLoadBalancer)
private bool DoesServerIdExist(string id) => _cachedRooms.ContainsKey(id);
private string GenerateRoomID()
{
const int LENGTH = 5;
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var randomID = "";
var random = new Random();
do
{
var random = new System.Random();
randomID = new string(Enumerable.Repeat(chars, LENGTH)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
@ -96,6 +36,17 @@ namespace LightReflectiveMirror
return randomID;
}
/// <summary>
/// Generates a random server ID.
/// </summary>
/// <returns></returns>
private string GetRandomServerID()
{
if (!Program.conf.UseLoadBalancer)
{
return GenerateRoomID();
}
else
{
// ping load balancer here
@ -107,20 +58,72 @@ namespace LightReflectiveMirror
}
/// <summary>
/// Checks if a server id already is in use.
/// This is called when a client wants to send data to another player.
/// </summary>
/// <param name="id">The ID to check for</param>
/// <returns></returns>
bool DoesServerIdExist(string id)
/// <param name="clientId">The ID of the client who is sending the data</param>
/// <param name="clientData">The binary data the client is sending</param>
/// <param name="channel">The channel the client is sending this data on</param>
/// <param name="sendTo">Who to relay the data to</param>
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);
}
}
}
public enum OpCodes
private void SendData(byte[] clientData, int channel, int sendTo)
{
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
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<byte>(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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
}
/// <summary>
/// Called when a client wants to request their own ID.
/// </summary>
/// <param name="clientId">The client requesting their ID</param>
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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
}
}
}

View file

@ -7,6 +7,55 @@ namespace LightReflectiveMirror
{
public partial class RelayHandler
{
/// <summary>
/// Creates a room on the LRM node.
/// </summary>
/// <param name="clientId">The client requesting to create a room</param>
/// <param name="maxPlayers">The maximum amount of players for this room</param>
/// <param name="serverName">The name for the server</param>
/// <param name="isPublic">Weather or not the server should show up on the server list</param>
/// <param name="serverData">Extra data the host can include</param>
/// <param name="useDirectConnect">Weather or not, the host is capable of doing direct connections</param>
/// <param name="hostLocalIP">The hosts local IP</param>
/// <param name="useNatPunch">Weather or not, the host is supporting NAT Punch</param>
/// <param name="port">The port of the direct connect transport on the host</param>
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<int>(),
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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
Endpoint.RoomsModified();
}
/// <summary>
/// Attempts to join a room for a client.
@ -15,7 +64,7 @@ namespace LightReflectiveMirror
/// <param name="serverId">The server ID of the room</param>
/// <param name="canDirectConnect">If the client is capable of a direct connection</param>
/// <param name="localIP">The local IP of the client joining</param>
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);
}
/// <summary>
/// Creates a room on the LRM node.
/// </summary>
/// <param name="clientId">The client requesting to create a room</param>
/// <param name="maxPlayers">The maximum amount of players for this room</param>
/// <param name="serverName">The name for the server</param>
/// <param name="isPublic">Weather or not the server should show up on the server list</param>
/// <param name="serverData">Extra data the host can include</param>
/// <param name="useDirectConnect">Weather or not, the host is capable of doing direct connections</param>
/// <param name="hostLocalIP">The hosts local IP</param>
/// <param name="useNatPunch">Weather or not, the host is supporting NAT Punch</param>
/// <param name="port">The port of the direct connect transport on the host</param>
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<int>(),
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<byte>(sendBuffer, 0, pos));
_sendBuffers.Return(sendBuffer);
Endpoint.RoomsModified();
}
/// <summary>
/// Makes the client leave their room.
/// </summary>
/// <param name="clientId">The client of which to remove from their room</param>
/// <param name="requiredHostId">The ID of the client who kicked the client. -1 if the client left on their own terms</param>
void LeaveRoom(int clientId, int requiredHostId = -1)
private void LeaveRoom(int clientId, int requiredHostId = -1)
{
for (int i = 0; i < rooms.Count; i++)
{

View file

@ -5,11 +5,18 @@ namespace LightReflectiveMirror
{
public partial class RelayHandler
{
public List<Room> rooms = new List<Room>();
private List<int> _pendingAuthentication = new List<int>();
public List<Room> rooms = new();
private List<int> _pendingAuthentication = new();
private ArrayPool<byte> _sendBuffers;
private int _maxPacketSize = 0;
private Dictionary<int, Room> _cachedClientRooms = new Dictionary<int, Room>();
private Dictionary<string, Room> _cachedRooms = new Dictionary<string, Room>();
private Dictionary<int, Room> _cachedClientRooms = new();
private Dictionary<string, Room> _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
}
}