Reformat, Begin packet refactors
* Reformat solution * Start to work on packet refactors to centralize serialization logic * Expand gitignore
This commit is contained in:
parent
e3c04d2363
commit
7d40531231
|
@ -1,2 +1,37 @@
|
|||
*.swp
|
||||
*.*~
|
||||
project.lock.json
|
||||
.DS_Store
|
||||
*.pyc
|
||||
nupkg/
|
||||
|
||||
.vs/CommunityServerAPI/v17/.suo
|
||||
# Visual Studio Code
|
||||
.vscode
|
||||
|
||||
# Rider
|
||||
.idea
|
||||
|
||||
# User-specific files
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
build/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
msbuild.log
|
||||
msbuild.err
|
||||
msbuild.wrn
|
||||
|
||||
# Visual Studio 2015
|
||||
.vs/
|
||||
|
|
|
@ -1,74 +1,92 @@
|
|||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Common.Extentions;
|
||||
using BattleBitAPI.Common.Serialization;
|
||||
using BattleBitAPI.Networking;
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
using System;
|
||||
#region
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace BattleBitAPI.Client
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Networking;
|
||||
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
using CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BattleBitAPI.Client;
|
||||
|
||||
// This class was created mainly for Unity Engine, for this reason, Task async was not implemented.
|
||||
public class Client
|
||||
{
|
||||
// This class was created mainly for Unity Engine, for this reason, Task async was not implemented.
|
||||
public class Client
|
||||
{
|
||||
// ---- Public Variables ----
|
||||
public bool IsConnected { get; private set; }
|
||||
public int GamePort { get; set; } = 30000;
|
||||
public bool IsPasswordProtected { get; set; } = false;
|
||||
public string ServerName { get; set; } = "";
|
||||
public string Gamemode { get; set; } = "";
|
||||
public string Map { get; set; } = "";
|
||||
public MapSize MapSize { get; set; } = MapSize._16vs16;
|
||||
public MapDayNight DayNight { get; set; } = MapDayNight.Day;
|
||||
public int CurrentPlayers { get; set; } = 0;
|
||||
public int InQueuePlayers { get; set; } = 0;
|
||||
public int MaxPlayers { get; set; } = 16;
|
||||
public string LoadingScreenText { get; set; } = "";
|
||||
public string ServerRulesText { get; set; } = "";
|
||||
private string mDestination;
|
||||
private bool mIsConnectingFlag;
|
||||
private byte[] mKeepAliveBuffer;
|
||||
private long mLastPackageReceived;
|
||||
private long mLastPackageSent;
|
||||
private int mPort;
|
||||
private uint mReadPackageSize;
|
||||
private Stream mReadStream;
|
||||
|
||||
// ---- Private Variables ----
|
||||
private TcpClient mSocket;
|
||||
private string mDestination;
|
||||
private int mPort;
|
||||
private byte[] mKeepAliveBuffer;
|
||||
private Common.Serialization.Stream mWriteStream;
|
||||
private Common.Serialization.Stream mReadStream;
|
||||
private uint mReadPackageSize;
|
||||
private long mLastPackageReceived;
|
||||
private long mLastPackageSent;
|
||||
private bool mIsConnectingFlag;
|
||||
private Stream mWriteStream;
|
||||
|
||||
// ---- Construction ----
|
||||
public Client(string destination, int port)
|
||||
{
|
||||
this.mDestination = destination;
|
||||
this.mPort = port;
|
||||
mDestination = destination;
|
||||
mPort = port;
|
||||
|
||||
this.mWriteStream = new Common.Serialization.Stream()
|
||||
mWriteStream = new Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0,
|
||||
WritePosition = 0
|
||||
};
|
||||
this.mReadStream = new Common.Serialization.Stream()
|
||||
mReadStream = new Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0,
|
||||
WritePosition = 0
|
||||
};
|
||||
this.mKeepAliveBuffer = new byte[4]
|
||||
mKeepAliveBuffer = new byte[4]
|
||||
{
|
||||
0,0,0,0,
|
||||
0, 0, 0, 0
|
||||
};
|
||||
|
||||
this.mLastPackageReceived = Extentions.TickCount;
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
mLastPackageReceived = Extensions.TickCount;
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
}
|
||||
|
||||
// ---- Public Variables ----
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
public int GamePort { get; set; } = 30000;
|
||||
|
||||
public bool IsPasswordProtected { get; set; } = false;
|
||||
|
||||
public string ServerName { get; set; } = "";
|
||||
|
||||
public string Gamemode { get; set; } = "";
|
||||
|
||||
public string Map { get; set; } = "";
|
||||
|
||||
public MapSize MapSize { get; set; } = MapSize._16vs16;
|
||||
|
||||
public MapDayNight DayNight { get; set; } = MapDayNight.Day;
|
||||
|
||||
public int CurrentPlayers { get; set; } = 0;
|
||||
|
||||
public int InQueuePlayers { get; set; } = 0;
|
||||
|
||||
public int MaxPlayers { get; set; } = 16;
|
||||
|
||||
public string LoadingScreenText { get; set; } = "";
|
||||
|
||||
public string ServerRulesText { get; set; } = "";
|
||||
|
||||
// ---- Main Tick ----
|
||||
public void Tick()
|
||||
{
|
||||
|
@ -77,30 +95,41 @@ namespace BattleBitAPI.Client
|
|||
return;
|
||||
|
||||
//Have we connected?
|
||||
if (!this.IsConnected)
|
||||
if (!IsConnected)
|
||||
{
|
||||
//Attempt to connect to server async.
|
||||
this.mIsConnectingFlag = true;
|
||||
mIsConnectingFlag = true;
|
||||
|
||||
//Dispose old client if exist.
|
||||
if (this.mSocket != null)
|
||||
if (mSocket != null)
|
||||
{
|
||||
try { this.mSocket.Close(); } catch { }
|
||||
try { this.mSocket.Dispose(); } catch { }
|
||||
this.mSocket = null;
|
||||
try
|
||||
{
|
||||
mSocket.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
mSocket.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
mSocket = null;
|
||||
}
|
||||
|
||||
//Create new client
|
||||
this.mSocket = new TcpClient();
|
||||
this.mSocket.SendBufferSize = Const.MaxNetworkPackageSize;
|
||||
this.mSocket.ReceiveBufferSize = Const.MaxNetworkPackageSize;
|
||||
mSocket = new TcpClient();
|
||||
mSocket.SendBufferSize = Const.MaxNetworkPackageSize;
|
||||
mSocket.ReceiveBufferSize = Const.MaxNetworkPackageSize;
|
||||
|
||||
//Attempt to connect.
|
||||
try
|
||||
{
|
||||
var state = mSocket.BeginConnect(mDestination, mPort, (x) =>
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
//Did we connect?
|
||||
|
@ -109,21 +138,21 @@ namespace BattleBitAPI.Client
|
|||
var networkStream = mSocket.GetStream();
|
||||
|
||||
//Prepare our hail package and send it.
|
||||
using (var hail = BattleBitAPI.Common.Serialization.Stream.Get())
|
||||
using (var hail = Stream.Get())
|
||||
{
|
||||
hail.Write((byte)NetworkCommuncation.Hail);
|
||||
hail.Write((ushort)this.GamePort);
|
||||
hail.Write(this.IsPasswordProtected);
|
||||
hail.Write(this.ServerName);
|
||||
hail.Write(this.Gamemode);
|
||||
hail.Write(this.Map);
|
||||
hail.Write((byte)this.MapSize);
|
||||
hail.Write((byte)this.DayNight);
|
||||
hail.Write((byte)this.CurrentPlayers);
|
||||
hail.Write((byte)this.InQueuePlayers);
|
||||
hail.Write((byte)this.MaxPlayers);
|
||||
hail.Write(this.LoadingScreenText);
|
||||
hail.Write(this.ServerRulesText);
|
||||
hail.Write((ushort)GamePort);
|
||||
hail.Write(IsPasswordProtected);
|
||||
hail.Write(ServerName);
|
||||
hail.Write(Gamemode);
|
||||
hail.Write(Map);
|
||||
hail.Write((byte)MapSize);
|
||||
hail.Write((byte)DayNight);
|
||||
hail.Write((byte)CurrentPlayers);
|
||||
hail.Write((byte)InQueuePlayers);
|
||||
hail.Write((byte)MaxPlayers);
|
||||
hail.Write(LoadingScreenText);
|
||||
hail.Write(ServerRulesText);
|
||||
|
||||
//Send our hail package.
|
||||
networkStream.Write(hail.Buffer, 0, hail.WritePosition);
|
||||
|
@ -134,7 +163,7 @@ namespace BattleBitAPI.Client
|
|||
var watch = Stopwatch.StartNew();
|
||||
|
||||
//Read the first byte.
|
||||
NetworkCommuncation response = NetworkCommuncation.None;
|
||||
var response = NetworkCommuncation.None;
|
||||
while (watch.ElapsedMilliseconds < Const.HailConnectTimeout)
|
||||
{
|
||||
if (mSocket.Available > 0)
|
||||
|
@ -153,8 +182,8 @@ namespace BattleBitAPI.Client
|
|||
if (response == NetworkCommuncation.Accepted)
|
||||
{
|
||||
//We are accepted.
|
||||
this.mIsConnectingFlag = false;
|
||||
this.IsConnected = true;
|
||||
mIsConnectingFlag = false;
|
||||
IsConnected = true;
|
||||
|
||||
mOnConnectedToServer();
|
||||
}
|
||||
|
@ -169,7 +198,7 @@ namespace BattleBitAPI.Client
|
|||
{
|
||||
string errorString = null;
|
||||
|
||||
using (var readStream = BattleBitAPI.Common.Serialization.Stream.Get())
|
||||
using (var readStream = Stream.Get())
|
||||
{
|
||||
readStream.WritePosition = networkStream.Read(readStream.Buffer, 0, mSocket.Available);
|
||||
if (!readStream.TryReadString(out errorString))
|
||||
|
@ -185,18 +214,16 @@ namespace BattleBitAPI.Client
|
|||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
this.mIsConnectingFlag = false;
|
||||
mIsConnectingFlag = false;
|
||||
|
||||
mLogError("Unable to connect to API server: " + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
}, null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
this.mIsConnectingFlag = false;
|
||||
mIsConnectingFlag = false;
|
||||
}
|
||||
|
||||
//We haven't connected yet.
|
||||
|
@ -219,89 +246,85 @@ namespace BattleBitAPI.Client
|
|||
//Read network packages.
|
||||
while (mSocket.Available > 0)
|
||||
{
|
||||
this.mLastPackageReceived = Extentions.TickCount;
|
||||
mLastPackageReceived = Extensions.TickCount;
|
||||
|
||||
//Do we know the package size?
|
||||
if (this.mReadPackageSize == 0)
|
||||
if (mReadPackageSize == 0)
|
||||
{
|
||||
const int sizeToRead = 4;
|
||||
int leftSizeToRead = sizeToRead - this.mReadStream.WritePosition;
|
||||
var leftSizeToRead = sizeToRead - mReadStream.WritePosition;
|
||||
|
||||
int read = networkStream.Read(this.mReadStream.Buffer, this.mReadStream.WritePosition, leftSizeToRead);
|
||||
var read = networkStream.Read(mReadStream.Buffer, mReadStream.WritePosition, leftSizeToRead);
|
||||
if (read <= 0)
|
||||
throw new Exception("Connection was terminated.");
|
||||
|
||||
this.mReadStream.WritePosition += read;
|
||||
mReadStream.WritePosition += read;
|
||||
|
||||
//Did we receive the package?
|
||||
if (this.mReadStream.WritePosition >= 4)
|
||||
if (mReadStream.WritePosition >= 4)
|
||||
{
|
||||
//Read the package size
|
||||
this.mReadPackageSize = this.mReadStream.ReadUInt32();
|
||||
mReadPackageSize = mReadStream.ReadUInt32();
|
||||
|
||||
if (this.mReadPackageSize > Const.MaxNetworkPackageSize)
|
||||
if (mReadPackageSize > Const.MaxNetworkPackageSize)
|
||||
throw new Exception("Incoming package was larger than 'Conts.MaxNetworkPackageSize'");
|
||||
|
||||
//Is this keep alive package?
|
||||
if (this.mReadPackageSize == 0)
|
||||
{
|
||||
if (mReadPackageSize == 0)
|
||||
Console.WriteLine("Keep alive was received.");
|
||||
}
|
||||
|
||||
//Reset the stream.
|
||||
this.mReadStream.Reset();
|
||||
mReadStream.Reset();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int sizeToRead = (int)mReadPackageSize;
|
||||
int leftSizeToRead = sizeToRead - this.mReadStream.WritePosition;
|
||||
var sizeToRead = (int)mReadPackageSize;
|
||||
var leftSizeToRead = sizeToRead - mReadStream.WritePosition;
|
||||
|
||||
int read = networkStream.Read(this.mReadStream.Buffer, this.mReadStream.WritePosition, leftSizeToRead);
|
||||
var read = networkStream.Read(mReadStream.Buffer, mReadStream.WritePosition, leftSizeToRead);
|
||||
if (read <= 0)
|
||||
throw new Exception("Connection was terminated.");
|
||||
|
||||
this.mReadStream.WritePosition += read;
|
||||
mReadStream.WritePosition += read;
|
||||
|
||||
//Do we have the package?
|
||||
if (this.mReadStream.WritePosition >= mReadPackageSize)
|
||||
if (mReadStream.WritePosition >= mReadPackageSize)
|
||||
{
|
||||
this.mReadPackageSize = 0;
|
||||
mReadPackageSize = 0;
|
||||
|
||||
mExecutePackage(this.mReadStream);
|
||||
mExecutePackage(mReadStream);
|
||||
|
||||
//Reset
|
||||
this.mReadStream.Reset();
|
||||
mReadStream.Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Send the network packages.
|
||||
if (this.mWriteStream.WritePosition > 0)
|
||||
if (mWriteStream.WritePosition > 0)
|
||||
lock (mWriteStream)
|
||||
{
|
||||
lock (this.mWriteStream)
|
||||
if (mWriteStream.WritePosition > 0)
|
||||
{
|
||||
if (this.mWriteStream.WritePosition > 0)
|
||||
{
|
||||
networkStream.Write(this.mWriteStream.Buffer, 0, this.mWriteStream.WritePosition);
|
||||
this.mWriteStream.WritePosition = 0;
|
||||
networkStream.Write(mWriteStream.Buffer, 0, mWriteStream.WritePosition);
|
||||
mWriteStream.WritePosition = 0;
|
||||
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
}
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
}
|
||||
}
|
||||
|
||||
//Are we timed out?
|
||||
if ((Extentions.TickCount - this.mLastPackageReceived) > Const.NetworkTimeout)
|
||||
if (Extensions.TickCount - mLastPackageReceived > Const.NetworkTimeout)
|
||||
throw new Exception("server timedout.");
|
||||
|
||||
//Send keep alive if needed
|
||||
if ((Extentions.TickCount - this.mLastPackageSent) > Const.NetworkKeepAlive)
|
||||
if (Extensions.TickCount - mLastPackageSent > Const.NetworkKeepAlive)
|
||||
{
|
||||
//Send keep alive.
|
||||
networkStream.Write(this.mKeepAliveBuffer, 0, 4);
|
||||
networkStream.Write(mKeepAliveBuffer, 0, 4);
|
||||
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
|
||||
Console.WriteLine("Keep alive was sent.");
|
||||
}
|
||||
|
@ -313,20 +336,19 @@ namespace BattleBitAPI.Client
|
|||
}
|
||||
|
||||
// ---- Internal ----
|
||||
private void mExecutePackage(Common.Serialization.Stream stream)
|
||||
private void mExecutePackage(Stream stream)
|
||||
{
|
||||
var communcation = (NetworkCommuncation)stream.ReadInt8();
|
||||
switch (communcation)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Callbacks ----
|
||||
private void mOnConnectedToServer()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
private void mOnDisconnectedFromServer(string reason)
|
||||
{
|
||||
}
|
||||
|
@ -335,24 +357,35 @@ namespace BattleBitAPI.Client
|
|||
// ---- Private ----
|
||||
private void mLogError(string str)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
private void mClose(string reason)
|
||||
{
|
||||
if (this.IsConnected)
|
||||
if (IsConnected)
|
||||
{
|
||||
this.IsConnected = false;
|
||||
IsConnected = false;
|
||||
|
||||
//Dispose old client if exist.
|
||||
if (this.mSocket != null)
|
||||
if (mSocket != null)
|
||||
{
|
||||
try { this.mSocket.Close(); } catch { }
|
||||
try { this.mSocket.Dispose(); } catch { }
|
||||
this.mSocket = null;
|
||||
try
|
||||
{
|
||||
mSocket.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
mSocket.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
mSocket = null;
|
||||
}
|
||||
|
||||
mOnDisconnectedFromServer(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +1,22 @@
|
|||
namespace CommunityServerAPI.BattleBitAPI
|
||||
namespace CommunityServerAPI.BattleBitAPI;
|
||||
|
||||
public static class Const
|
||||
{
|
||||
public static class Const
|
||||
{
|
||||
// ---- Networking ----
|
||||
/// <summary>
|
||||
/// Maximum data size for a single package. 4MB is default.
|
||||
/// </summary>
|
||||
public const int MaxNetworkPackageSize = 1024 * 1024 * 4;//4mb
|
||||
public const int MaxNetworkPackageSize = 1024 * 1024 * 4; //4mb
|
||||
/// <summary>
|
||||
/// How long should server/client wait until connection is determined as timed out when no packages is being sent for long time.
|
||||
/// How long should server/client wait until connection is determined as timed out when no packages
|
||||
/// is being sent for long time.
|
||||
/// </summary>
|
||||
public const int NetworkTimeout = 60 * 1000;//60 seconds
|
||||
public const int NetworkTimeout = 60 * 1000; //60 seconds
|
||||
/// <summary>
|
||||
/// How frequently client/server will send keep alive to each other when no message is being sent to each other for a while.
|
||||
/// How frequently client/server will send keep alive to each other when no message is being sent
|
||||
/// to each other for a while.
|
||||
/// </summary>
|
||||
public const int NetworkKeepAlive = 15 * 1000;//15 seconds
|
||||
public const int NetworkKeepAlive = 15 * 1000; //15 seconds
|
||||
/// <summary>
|
||||
/// How long server/client will wait other side to send their hail/initial package. In miliseconds.
|
||||
/// </summary>
|
||||
|
@ -35,6 +37,4 @@
|
|||
|
||||
public const int MinServerRulesTextLength = 0;
|
||||
public const int MaxServerRulesTextLength = 1024 * 8;
|
||||
|
||||
}
|
||||
}
|
|
@ -1,8 +1,7 @@
|
|||
namespace BattleBitAPI.Common.Enums
|
||||
namespace BattleBitAPI.Common.Enums;
|
||||
|
||||
public enum MapDayNight : byte
|
||||
{
|
||||
public enum MapDayNight : byte
|
||||
{
|
||||
Day = 0,
|
||||
Night = 1,
|
||||
}
|
||||
Night = 1
|
||||
}
|
|
@ -1,10 +1,9 @@
|
|||
namespace BattleBitAPI.Common.Enums
|
||||
namespace BattleBitAPI.Common.Enums;
|
||||
|
||||
public enum MapSize : byte
|
||||
{
|
||||
public enum MapSize : byte
|
||||
{
|
||||
_16vs16 = 0,
|
||||
_32vs32 = 1,
|
||||
_64vs64 = 2,
|
||||
_127vs127 = 3,
|
||||
}
|
||||
_127vs127 = 3
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
#region
|
||||
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
public static class Extensions
|
||||
{
|
||||
public static long TickCount
|
||||
{
|
||||
get
|
||||
{
|
||||
#if NETCOREAPP
|
||||
return Environment.TickCount64;
|
||||
#else
|
||||
return (long)Environment.TickCount;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
public static unsafe uint ToUInt(this IPAddress address)
|
||||
{
|
||||
#if NETCOREAPP
|
||||
return BitConverter.ToUInt32(address.GetAddressBytes());
|
||||
#else
|
||||
return BitConverter.ToUInt32(address.GetAddressBytes(), 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
public static void SafeClose(this TcpClient client)
|
||||
{
|
||||
try
|
||||
{
|
||||
client.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
client.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,82 +0,0 @@
|
|||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace BattleBitAPI.Common.Extentions
|
||||
{
|
||||
public static class Extentions
|
||||
{
|
||||
public static long TickCount
|
||||
{
|
||||
get
|
||||
{
|
||||
#if NETCOREAPP
|
||||
return System.Environment.TickCount64;
|
||||
#else
|
||||
return (long)Environment.TickCount;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
public unsafe static uint ToUInt(this IPAddress address)
|
||||
{
|
||||
#if NETCOREAPP
|
||||
return BitConverter.ToUInt32(address.GetAddressBytes());
|
||||
#else
|
||||
return BitConverter.ToUInt32(address.GetAddressBytes(), 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
public static void SafeClose(this TcpClient client)
|
||||
{
|
||||
try { client.Close(); } catch { }
|
||||
try { client.Dispose(); } catch { }
|
||||
}
|
||||
public static async Task<int> Read(this NetworkStream networkStream, Serialization.Stream outputStream, int size, CancellationToken token = default)
|
||||
{
|
||||
int read = 0;
|
||||
int readUntil = outputStream.WritePosition + size;
|
||||
|
||||
//Ensure we have space.
|
||||
outputStream.EnsureWriteBufferSize(size);
|
||||
|
||||
//Continue reading until we have the package.
|
||||
while (outputStream.WritePosition < readUntil)
|
||||
{
|
||||
int sizeToRead = readUntil - outputStream.WritePosition;
|
||||
int received = await networkStream.ReadAsync(outputStream.Buffer, outputStream.WritePosition, sizeToRead, token);
|
||||
if (received <= 0)
|
||||
throw new Exception("NetworkStream was closed.");
|
||||
|
||||
read += received;
|
||||
outputStream.WritePosition += received;
|
||||
}
|
||||
|
||||
return read;
|
||||
}
|
||||
public static async Task<bool> TryRead(this NetworkStream networkStream, Serialization.Stream outputStream, int size, CancellationToken token = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
int readUntil = outputStream.WritePosition + size;
|
||||
|
||||
//Ensure we have space.
|
||||
outputStream.EnsureWriteBufferSize(size);
|
||||
|
||||
//Continue reading until we have the package.
|
||||
while (outputStream.WritePosition < readUntil)
|
||||
{
|
||||
int sizeToRead = readUntil - outputStream.WritePosition;
|
||||
int received = await networkStream.ReadAsync(outputStream.Buffer, outputStream.WritePosition, sizeToRead, token);
|
||||
if (received <= 0)
|
||||
throw new Exception("NetworkStream was closed.");
|
||||
outputStream.WritePosition += received;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
#region
|
||||
|
||||
using System.Net.Sockets;
|
||||
|
||||
using CommunityServerAPI.BattleBitAPI.Packets;
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
public static class NetworkStreamExtensions
|
||||
{
|
||||
public static async Task<int> Read(this NetworkStream networkStream, Stream outputStream, int size, CancellationToken token = default)
|
||||
{
|
||||
var read = 0;
|
||||
var readUntil = outputStream.WritePosition + size;
|
||||
|
||||
//Ensure we have space.
|
||||
outputStream.EnsureWriteBufferSize(size);
|
||||
|
||||
//Continue reading until we have the package.
|
||||
while (outputStream.WritePosition < readUntil)
|
||||
{
|
||||
var sizeToRead = readUntil - outputStream.WritePosition;
|
||||
var received = await networkStream.ReadAsync(outputStream.Buffer, outputStream.WritePosition, sizeToRead, token);
|
||||
if (received <= 0)
|
||||
throw new Exception("NetworkStream was closed.");
|
||||
|
||||
read += received;
|
||||
outputStream.WritePosition += received;
|
||||
}
|
||||
|
||||
return read;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize the provided packet and send it down the network stream.
|
||||
/// Returns false if an error occured, true otherwise.
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <param name="packet"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task<bool> TryWritePacket(this NetworkStream self, BasePacket packet)
|
||||
{
|
||||
using (var stream = Stream.Get())
|
||||
{
|
||||
if (!packet.TryWrite(stream))
|
||||
return false;
|
||||
|
||||
self.Write(stream.Buffer, 0, stream.WritePosition);
|
||||
self.Flush();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static async Task<bool> TryRead(this NetworkStream networkStream, Stream outputStream, int size, CancellationToken token = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var readUntil = outputStream.WritePosition + size;
|
||||
|
||||
//Ensure we have space.
|
||||
outputStream.EnsureWriteBufferSize(size);
|
||||
|
||||
//Continue reading until we have the package.
|
||||
while (outputStream.WritePosition < readUntil)
|
||||
{
|
||||
var sizeToRead = readUntil - outputStream.WritePosition;
|
||||
var received = await networkStream.ReadAsync(outputStream.Buffer, outputStream.WritePosition, sizeToRead, token);
|
||||
if (received <= 0)
|
||||
throw new Exception("NetworkStream was closed.");
|
||||
outputStream.WritePosition += received;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,8 +1,8 @@
|
|||
namespace BattleBitAPI.Common.Serialization
|
||||
namespace BattleBitAPI.Common.Serialization;
|
||||
|
||||
public interface IStreamSerializable
|
||||
{
|
||||
public interface IStreamSerializable
|
||||
{
|
||||
void Read(Stream ser);
|
||||
|
||||
void Write(Stream ser);
|
||||
}
|
||||
}
|
|
@ -1,10 +1,16 @@
|
|||
using BattleBitAPI.Common.Extentions;
|
||||
using System.Net;
|
||||
#region
|
||||
|
||||
namespace BattleBitAPI.Common.Serialization
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
using CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BattleBitAPI.Common.Serialization;
|
||||
|
||||
public class Stream : IDisposable
|
||||
{
|
||||
public class Stream : IDisposable
|
||||
{
|
||||
public const int DefaultBufferSize = 1024 * 512;
|
||||
|
||||
#if BIGENDIAN
|
||||
|
@ -20,18 +26,19 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
public bool CanRead(int size)
|
||||
{
|
||||
int readableLenght = WritePosition - ReadPosition;
|
||||
return (readableLenght >= size);
|
||||
var readableLenght = WritePosition - ReadPosition;
|
||||
return readableLenght >= size;
|
||||
}
|
||||
|
||||
public void EnsureWriteBufferSize(int requiredSize)
|
||||
{
|
||||
int bufferLenght = Buffer.Length;
|
||||
var bufferLenght = Buffer.Length;
|
||||
|
||||
int leftSpace = bufferLenght - WritePosition;
|
||||
var leftSpace = bufferLenght - WritePosition;
|
||||
if (leftSpace < requiredSize)
|
||||
{
|
||||
int newSize = bufferLenght + Math.Max(requiredSize, 1024);
|
||||
System.Array.Resize(ref Buffer, newSize);
|
||||
var newSize = bufferLenght + Math.Max(requiredSize, 1024);
|
||||
Array.Resize(ref Buffer, newSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -42,200 +49,257 @@ namespace BattleBitAPI.Common.Serialization
|
|||
Buffer[WritePosition] = value;
|
||||
WritePosition += 1;
|
||||
}
|
||||
|
||||
public void Write(bool value)
|
||||
{
|
||||
EnsureWriteBufferSize(1);
|
||||
Buffer[WritePosition] = value ? (byte)1 : (byte)0;
|
||||
WritePosition += 1;
|
||||
}
|
||||
|
||||
public unsafe void Write(short value)
|
||||
{
|
||||
EnsureWriteBufferSize(2);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((short*)ptr) = value;
|
||||
{
|
||||
*(short*)ptr = value;
|
||||
}
|
||||
WritePosition += 2;
|
||||
}
|
||||
|
||||
public unsafe void Write(ushort value)
|
||||
{
|
||||
EnsureWriteBufferSize(2);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((ushort*)ptr) = value;
|
||||
{
|
||||
*(ushort*)ptr = value;
|
||||
}
|
||||
WritePosition += 2;
|
||||
}
|
||||
|
||||
public unsafe void Write(int value)
|
||||
{
|
||||
EnsureWriteBufferSize(4);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((int*)ptr) = value;
|
||||
{
|
||||
*(int*)ptr = value;
|
||||
}
|
||||
WritePosition += 4;
|
||||
}
|
||||
|
||||
public unsafe void Write(uint value)
|
||||
{
|
||||
EnsureWriteBufferSize(4);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((uint*)ptr) = value;
|
||||
{
|
||||
*(uint*)ptr = value;
|
||||
}
|
||||
WritePosition += 4;
|
||||
}
|
||||
|
||||
public unsafe void Write(long value)
|
||||
{
|
||||
EnsureWriteBufferSize(8);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((long*)ptr) = value;
|
||||
{
|
||||
*(long*)ptr = value;
|
||||
}
|
||||
WritePosition += 8;
|
||||
}
|
||||
|
||||
public unsafe void Write(ulong value)
|
||||
{
|
||||
EnsureWriteBufferSize(8);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((ulong*)ptr) = value;
|
||||
{
|
||||
*(ulong*)ptr = value;
|
||||
}
|
||||
WritePosition += 8;
|
||||
}
|
||||
|
||||
public unsafe void Write(decimal value)
|
||||
{
|
||||
EnsureWriteBufferSize(16);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((decimal*)ptr) = value;
|
||||
{
|
||||
*(decimal*)ptr = value;
|
||||
}
|
||||
WritePosition += 16;
|
||||
}
|
||||
|
||||
public unsafe void Write(double value)
|
||||
{
|
||||
EnsureWriteBufferSize(16);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((double*)ptr) = value;
|
||||
{
|
||||
*(double*)ptr = value;
|
||||
}
|
||||
WritePosition += 16;
|
||||
}
|
||||
|
||||
public unsafe void Write(float value)
|
||||
{
|
||||
int intValue = *((int*)&value);
|
||||
var intValue = *(int*)&value;
|
||||
EnsureWriteBufferSize(4);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((int*)ptr) = intValue;
|
||||
{
|
||||
*(int*)ptr = intValue;
|
||||
}
|
||||
WritePosition += 4;
|
||||
}
|
||||
|
||||
public unsafe void Write(string value)
|
||||
{
|
||||
int charCount = value.Length;
|
||||
var charCount = value.Length;
|
||||
fixed (char* strPtr = value)
|
||||
{
|
||||
int size = System.Text.Encoding.UTF8.GetByteCount(strPtr, charCount);
|
||||
var size = Encoding.UTF8.GetByteCount(strPtr, charCount);
|
||||
EnsureWriteBufferSize(size + 2);
|
||||
|
||||
|
||||
fixed (byte* buffPtr = &Buffer[WritePosition])
|
||||
{
|
||||
*((ushort*)buffPtr) = (ushort)size;
|
||||
System.Text.Encoding.UTF8.GetBytes(strPtr, charCount, buffPtr + 2, size);
|
||||
*(ushort*)buffPtr = (ushort)size;
|
||||
Encoding.UTF8.GetBytes(strPtr, charCount, buffPtr + 2, size);
|
||||
}
|
||||
WritePosition += size + 2;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Write(DateTime value)
|
||||
{
|
||||
var utc = value.ToUniversalTime();
|
||||
|
||||
EnsureWriteBufferSize(8);
|
||||
fixed (byte* ptr = &Buffer[WritePosition])
|
||||
*((long*)ptr) = utc.Ticks;
|
||||
{
|
||||
*(long*)ptr = utc.Ticks;
|
||||
}
|
||||
WritePosition += 8;
|
||||
}
|
||||
|
||||
public unsafe void Write(IPAddress value)
|
||||
{
|
||||
uint ip = value.ToUInt();
|
||||
var ip = value.ToUInt();
|
||||
Write(ip);
|
||||
}
|
||||
|
||||
public unsafe void Write(IPEndPoint value)
|
||||
{
|
||||
uint ip = value.Address.ToUInt();
|
||||
var ip = value.Address.ToUInt();
|
||||
|
||||
Write(ip);
|
||||
Write((ushort)value.Port);
|
||||
}
|
||||
|
||||
public unsafe void WriteRaw(string value)
|
||||
{
|
||||
int charCount = value.Length;
|
||||
var charCount = value.Length;
|
||||
fixed (char* strPtr = value)
|
||||
{
|
||||
int size = System.Text.Encoding.UTF8.GetByteCount(strPtr, charCount);
|
||||
var size = Encoding.UTF8.GetByteCount(strPtr, charCount);
|
||||
EnsureWriteBufferSize(size);
|
||||
|
||||
fixed (byte* buffPtr = &Buffer[WritePosition])
|
||||
System.Text.Encoding.UTF8.GetBytes(strPtr, charCount, buffPtr, size);
|
||||
{
|
||||
Encoding.UTF8.GetBytes(strPtr, charCount, buffPtr, size);
|
||||
}
|
||||
WritePosition += size;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Write<T>(T value) where T : IStreamSerializable
|
||||
{
|
||||
value.Write(this);
|
||||
}
|
||||
|
||||
public void Write(byte[] source, int sourceIndex, int length)
|
||||
{
|
||||
if (length == 0)
|
||||
return;
|
||||
|
||||
EnsureWriteBufferSize(length);
|
||||
System.Array.Copy(source, sourceIndex, this.Buffer, this.WritePosition, length);
|
||||
this.WritePosition += length;
|
||||
Array.Copy(source, sourceIndex, Buffer, WritePosition, length);
|
||||
WritePosition += length;
|
||||
}
|
||||
|
||||
public void Write(Stream source)
|
||||
{
|
||||
EnsureWriteBufferSize(source.WritePosition);
|
||||
System.Array.Copy(source.Buffer, 0, this.Buffer, this.WritePosition, source.WritePosition);
|
||||
this.WritePosition += source.WritePosition;
|
||||
Array.Copy(source.Buffer, 0, Buffer, WritePosition, source.WritePosition);
|
||||
WritePosition += source.WritePosition;
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(byte value, int position)
|
||||
{
|
||||
Buffer[position] = value;
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(short value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((short*)ptr) = value;
|
||||
{
|
||||
*(short*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(ushort value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((ushort*)ptr) = value;
|
||||
{
|
||||
*(ushort*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(int value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((int*)ptr) = value;
|
||||
{
|
||||
*(int*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(uint value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((uint*)ptr) = value;
|
||||
{
|
||||
*(uint*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(long value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((long*)ptr) = value;
|
||||
{
|
||||
*(long*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteAt(ulong value, int position)
|
||||
{
|
||||
fixed (byte* ptr = &Buffer[position])
|
||||
*((ulong*)ptr) = value;
|
||||
{
|
||||
*(ulong*)ptr = value;
|
||||
}
|
||||
}
|
||||
|
||||
// -------- Read ------
|
||||
public byte ReadInt8()
|
||||
{
|
||||
|
||||
var value = Buffer[ReadPosition];
|
||||
ReadPosition++;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public bool ReadBool()
|
||||
{
|
||||
|
||||
|
||||
var value = Buffer[ReadPosition];
|
||||
ReadPosition++;
|
||||
|
||||
return value == 1;
|
||||
}
|
||||
|
||||
public unsafe short ReadInt16()
|
||||
{
|
||||
short value = 0;
|
||||
|
@ -244,24 +308,21 @@ namespace BattleBitAPI.Common.Serialization
|
|||
{
|
||||
if (ReadPosition % 2 == 0)
|
||||
{
|
||||
value = *((short*)pbyte);
|
||||
value = *(short*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
value = (short)((*pbyte) | (*(pbyte + 1) << 8));
|
||||
}
|
||||
value = (short)(*pbyte | (*(pbyte + 1) << 8));
|
||||
else
|
||||
{
|
||||
value = (short)((*pbyte << 8) | (*(pbyte + 1)));
|
||||
}
|
||||
value = (short)((*pbyte << 8) | *(pbyte + 1));
|
||||
}
|
||||
}
|
||||
|
||||
ReadPosition += 2;
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe ushort ReadUInt16()
|
||||
{
|
||||
ushort value = 0;
|
||||
|
@ -270,49 +331,43 @@ namespace BattleBitAPI.Common.Serialization
|
|||
{
|
||||
if (ReadPosition % 2 == 0)
|
||||
{
|
||||
value = *((ushort*)pbyte);
|
||||
value = *(ushort*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
value = (ushort)((*pbyte) | (*(pbyte + 1) << 8));
|
||||
}
|
||||
value = (ushort)(*pbyte | (*(pbyte + 1) << 8));
|
||||
else
|
||||
{
|
||||
value = (ushort)((*pbyte << 8) | (*(pbyte + 1)));
|
||||
}
|
||||
value = (ushort)((*pbyte << 8) | *(pbyte + 1));
|
||||
}
|
||||
}
|
||||
|
||||
ReadPosition += 2;
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe int ReadInt32()
|
||||
{
|
||||
int value = 0;
|
||||
var value = 0;
|
||||
fixed (byte* pbyte = &Buffer[ReadPosition])
|
||||
{
|
||||
if (ReadPosition % 4 == 0)
|
||||
{
|
||||
value = *((int*)pbyte);
|
||||
value = *(int*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
value = (int)((*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
}
|
||||
value = (int)(*pbyte | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
else
|
||||
{
|
||||
value = (int)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)));
|
||||
}
|
||||
value = (int)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | *(pbyte + 3));
|
||||
}
|
||||
}
|
||||
ReadPosition += 4;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe uint ReadUInt32()
|
||||
{
|
||||
uint value = 0;
|
||||
|
@ -320,24 +375,21 @@ namespace BattleBitAPI.Common.Serialization
|
|||
{
|
||||
if (ReadPosition % 4 == 0)
|
||||
{
|
||||
value = *((uint*)pbyte);
|
||||
value = *(uint*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
value = (uint)((*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
}
|
||||
value = (uint)(*pbyte | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
else
|
||||
{
|
||||
value = (uint)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)));
|
||||
}
|
||||
value = (uint)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | *(pbyte + 3));
|
||||
}
|
||||
}
|
||||
ReadPosition += 4;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe long ReadInt64()
|
||||
{
|
||||
long value = 0;
|
||||
|
@ -345,20 +397,20 @@ namespace BattleBitAPI.Common.Serialization
|
|||
{
|
||||
if (ReadPosition % 8 == 0)
|
||||
{
|
||||
value = *((long*)pbyte);
|
||||
value = *(long*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
|
||||
int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
|
||||
var i1 = *pbyte | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
|
||||
var i2 = *(pbyte + 4) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
|
||||
value = (uint)i1 | ((long)i2 << 32);
|
||||
}
|
||||
else
|
||||
{
|
||||
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
|
||||
int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
|
||||
var i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | *(pbyte + 3);
|
||||
var i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | *(pbyte + 7);
|
||||
value = (uint)i2 | ((long)i1 << 32);
|
||||
}
|
||||
}
|
||||
|
@ -367,6 +419,7 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe ulong ReadUInt64()
|
||||
{
|
||||
ulong value = 0;
|
||||
|
@ -374,20 +427,20 @@ namespace BattleBitAPI.Common.Serialization
|
|||
{
|
||||
if (ReadPosition % 8 == 0)
|
||||
{
|
||||
value = *((ulong*)pbyte);
|
||||
value = *(ulong*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
|
||||
int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
|
||||
var i1 = *pbyte | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
|
||||
var i2 = *(pbyte + 4) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
|
||||
value = (uint)i1 | ((ulong)i2 << 32);
|
||||
}
|
||||
else
|
||||
{
|
||||
int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
|
||||
int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
|
||||
var i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | *(pbyte + 3);
|
||||
var i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | *(pbyte + 7);
|
||||
value = (uint)i2 | ((ulong)i1 << 32);
|
||||
}
|
||||
}
|
||||
|
@ -396,58 +449,56 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe decimal ReadInt128()
|
||||
{
|
||||
|
||||
|
||||
decimal value = 0;
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
{
|
||||
value = *((decimal*)ptr);
|
||||
value = *(decimal*)ptr;
|
||||
}
|
||||
ReadPosition += 16;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe double ReadDouble()
|
||||
{
|
||||
double value = 0;
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
{
|
||||
value = *((double*)ptr);
|
||||
value = *(double*)ptr;
|
||||
}
|
||||
ReadPosition += 16;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public unsafe float ReadFloat()
|
||||
{
|
||||
int value = 0;
|
||||
var value = 0;
|
||||
fixed (byte* pbyte = &Buffer[ReadPosition])
|
||||
{
|
||||
if (ReadPosition % 4 == 0)
|
||||
{
|
||||
value = *((int*)pbyte);
|
||||
value = *(int*)pbyte;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsLittleEndian)
|
||||
{
|
||||
value = (int)((*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
}
|
||||
value = (int)(*pbyte | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
|
||||
else
|
||||
{
|
||||
value = (int)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)));
|
||||
}
|
||||
value = (int)((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | *(pbyte + 3));
|
||||
}
|
||||
}
|
||||
ReadPosition += 4;
|
||||
|
||||
return *(float*)&value;
|
||||
}
|
||||
|
||||
public DateTime ReadDateTime()
|
||||
{
|
||||
long value = ReadInt64();
|
||||
var value = ReadInt64();
|
||||
try
|
||||
{
|
||||
return new DateTime(value, DateTimeKind.Utc);
|
||||
|
@ -457,31 +508,37 @@ namespace BattleBitAPI.Common.Serialization
|
|||
return DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryReadDateTime(out DateTime time)
|
||||
{
|
||||
long value = ReadInt64();
|
||||
var value = ReadInt64();
|
||||
try
|
||||
{
|
||||
time = new DateTime(value, DateTimeKind.Utc);
|
||||
return true;
|
||||
}
|
||||
catch { }
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
time = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public unsafe IPAddress ReadIPAddress()
|
||||
{
|
||||
uint ip = ReadUInt32();
|
||||
var ip = ReadUInt32();
|
||||
return new IPAddress(ip);
|
||||
}
|
||||
|
||||
public unsafe IPEndPoint ReadIPEndPoint()
|
||||
{
|
||||
uint ip = ReadUInt32();
|
||||
ushort port = ReadUInt16();
|
||||
var ip = ReadUInt32();
|
||||
var port = ReadUInt16();
|
||||
|
||||
return new IPEndPoint(ip, port);
|
||||
}
|
||||
|
||||
public T Read<T>() where T : IStreamSerializable
|
||||
{
|
||||
T value = default;
|
||||
|
@ -494,23 +551,27 @@ namespace BattleBitAPI.Common.Serialization
|
|||
if (lenght == 0)
|
||||
return new byte[0];
|
||||
|
||||
byte[] newBuffer = new byte[lenght];
|
||||
System.Array.Copy(this.Buffer, this.ReadPosition, newBuffer, 0, lenght);
|
||||
this.ReadPosition += lenght;
|
||||
var newBuffer = new byte[lenght];
|
||||
Array.Copy(Buffer, ReadPosition, newBuffer, 0, lenght);
|
||||
ReadPosition += lenght;
|
||||
return newBuffer;
|
||||
}
|
||||
|
||||
public void ReadTo(byte[] buffer, int offset, int size)
|
||||
{
|
||||
System.Array.Copy(this.Buffer, this.ReadPosition, buffer, offset, size);
|
||||
this.ReadPosition += size;
|
||||
Array.Copy(Buffer, ReadPosition, buffer, offset, size);
|
||||
ReadPosition += size;
|
||||
}
|
||||
|
||||
public unsafe string ReadString(int size)
|
||||
{
|
||||
string str;
|
||||
|
||||
#if NETCOREAPP
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
str = System.Text.Encoding.UTF8.GetString(ptr, size);
|
||||
{
|
||||
str = Encoding.UTF8.GetString(ptr, size);
|
||||
}
|
||||
#else
|
||||
str = System.Text.Encoding.UTF8.GetString(Buffer, ReadPosition, size);
|
||||
#endif
|
||||
|
@ -518,6 +579,7 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
return str;
|
||||
}
|
||||
|
||||
public unsafe bool TryReadString(out string str)
|
||||
{
|
||||
if (!CanRead(2))
|
||||
|
@ -527,9 +589,11 @@ namespace BattleBitAPI.Common.Serialization
|
|||
}
|
||||
|
||||
|
||||
int size = 0;
|
||||
var size = 0;
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
size = *((ushort*)ptr);
|
||||
{
|
||||
size = *(ushort*)ptr;
|
||||
}
|
||||
ReadPosition += 2;
|
||||
|
||||
if (!CanRead(size))
|
||||
|
@ -540,7 +604,9 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
#if NETCOREAPP
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
str = System.Text.Encoding.UTF8.GetString(ptr, size);
|
||||
{
|
||||
str = Encoding.UTF8.GetString(ptr, size);
|
||||
}
|
||||
#else
|
||||
str = System.Text.Encoding.UTF8.GetString(Buffer, ReadPosition, size);
|
||||
#endif
|
||||
|
@ -549,6 +615,7 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
return true;
|
||||
}
|
||||
|
||||
public unsafe bool TryReadString(out string str, int maximumSize = ushort.MaxValue)
|
||||
{
|
||||
if (!CanRead(2))
|
||||
|
@ -558,9 +625,11 @@ namespace BattleBitAPI.Common.Serialization
|
|||
}
|
||||
|
||||
|
||||
int size = 0;
|
||||
var size = 0;
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
size = *((ushort*)ptr);
|
||||
{
|
||||
size = *(ushort*)ptr;
|
||||
}
|
||||
ReadPosition += 2;
|
||||
|
||||
if (size > maximumSize)
|
||||
|
@ -577,7 +646,9 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
#if NETCOREAPP
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
str = System.Text.Encoding.UTF8.GetString(ptr, size);
|
||||
{
|
||||
str = Encoding.UTF8.GetString(ptr, size);
|
||||
}
|
||||
#else
|
||||
str = System.Text.Encoding.UTF8.GetString(Buffer, ReadPosition, size);
|
||||
#endif
|
||||
|
@ -586,14 +657,17 @@ namespace BattleBitAPI.Common.Serialization
|
|||
|
||||
return true;
|
||||
}
|
||||
|
||||
public unsafe bool TrySkipString()
|
||||
{
|
||||
if (!CanRead(2))
|
||||
return false;
|
||||
|
||||
int size = 0;
|
||||
var size = 0;
|
||||
fixed (byte* ptr = &Buffer[ReadPosition])
|
||||
size = *((ushort*)ptr);
|
||||
{
|
||||
size = *(ushort*)ptr;
|
||||
}
|
||||
ReadPosition += 2;
|
||||
|
||||
if (!CanRead(size))
|
||||
|
@ -603,15 +677,14 @@ namespace BattleBitAPI.Common.Serialization
|
|||
return true;
|
||||
}
|
||||
|
||||
public int NumberOfBytesReadable
|
||||
{
|
||||
get => WritePosition - ReadPosition;
|
||||
}
|
||||
public int NumberOfBytesReadable => WritePosition - ReadPosition;
|
||||
|
||||
public void SkipWriting(int size)
|
||||
{
|
||||
EnsureWriteBufferSize(size);
|
||||
WritePosition += size;
|
||||
}
|
||||
|
||||
public void SkipReading(int size)
|
||||
{
|
||||
ReadPosition += size;
|
||||
|
@ -620,15 +693,15 @@ namespace BattleBitAPI.Common.Serialization
|
|||
// -------- Finalizing ------
|
||||
public byte[] AsByteArrayData()
|
||||
{
|
||||
var data = new byte[this.WritePosition];
|
||||
System.Array.Copy(this.Buffer, 0, data, 0, this.WritePosition);
|
||||
var data = new byte[WritePosition];
|
||||
Array.Copy(Buffer, 0, data, 0, WritePosition);
|
||||
return data;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
this.ReadPosition = 0;
|
||||
this.WritePosition = 0;
|
||||
ReadPosition = 0;
|
||||
WritePosition = 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
@ -638,11 +711,14 @@ namespace BattleBitAPI.Common.Serialization
|
|||
InPool = true;
|
||||
|
||||
lock (mPool)
|
||||
{
|
||||
mPool.Enqueue(this);
|
||||
}
|
||||
}
|
||||
|
||||
// ------- Pool -----
|
||||
private static Queue<Stream> mPool = new Queue<Stream>(1024 * 256);
|
||||
private static Queue<Stream> mPool = new(1024 * 256);
|
||||
|
||||
public static Stream Get()
|
||||
{
|
||||
lock (mPool)
|
||||
|
@ -663,8 +739,7 @@ namespace BattleBitAPI.Common.Serialization
|
|||
Buffer = new byte[DefaultBufferSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0,
|
||||
WritePosition = 0
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,21 +1,25 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
namespace BattleBitAPI.Common.Threading;
|
||||
|
||||
namespace BattleBitAPI.Common.Threading
|
||||
public class ThreadSafe<T>
|
||||
{
|
||||
public class ThreadSafe<T>
|
||||
{
|
||||
private System.Threading.ReaderWriterLockSlim mLock;
|
||||
private ReaderWriterLockSlim mLock;
|
||||
public T Value;
|
||||
|
||||
public ThreadSafe(T value)
|
||||
{
|
||||
this.Value = value;
|
||||
this.mLock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.SupportsRecursion);
|
||||
Value = value;
|
||||
mLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
|
||||
}
|
||||
|
||||
public SafeWriteHandle GetWriteHandle() => new SafeWriteHandle(this.mLock);
|
||||
public SafeReadHandle GetReadHandle() => new SafeReadHandle(this.mLock);
|
||||
public SafeWriteHandle GetWriteHandle()
|
||||
{
|
||||
return new(mLock);
|
||||
}
|
||||
|
||||
public SafeReadHandle GetReadHandle()
|
||||
{
|
||||
return new(mLock);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Swaps current value with new value and returns old one.
|
||||
|
@ -24,23 +28,26 @@ namespace BattleBitAPI.Common.Threading
|
|||
/// <returns>Old value</returns>
|
||||
public T SwapValue(T newValue)
|
||||
{
|
||||
using (new SafeWriteHandle(this.mLock))
|
||||
using (new SafeWriteHandle(mLock))
|
||||
{
|
||||
var oldValue = this.Value;
|
||||
this.Value = newValue;
|
||||
var oldValue = Value;
|
||||
Value = newValue;
|
||||
return oldValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
public class SafeWriteHandle : System.IDisposable
|
||||
{
|
||||
private System.Threading.ReaderWriterLockSlim mLock;
|
||||
}
|
||||
|
||||
public class SafeWriteHandle : IDisposable
|
||||
{
|
||||
private bool mDisposed;
|
||||
public SafeWriteHandle(System.Threading.ReaderWriterLockSlim mLock)
|
||||
private ReaderWriterLockSlim mLock;
|
||||
|
||||
public SafeWriteHandle(ReaderWriterLockSlim mLock)
|
||||
{
|
||||
this.mLock = mLock;
|
||||
mLock.EnterWriteLock();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (mDisposed)
|
||||
|
@ -48,16 +55,19 @@ namespace BattleBitAPI.Common.Threading
|
|||
mDisposed = true;
|
||||
mLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
public class SafeReadHandle : System.IDisposable
|
||||
{
|
||||
private System.Threading.ReaderWriterLockSlim mLock;
|
||||
}
|
||||
|
||||
public class SafeReadHandle : IDisposable
|
||||
{
|
||||
private bool mDisposed;
|
||||
public SafeReadHandle(System.Threading.ReaderWriterLockSlim mLock)
|
||||
private ReaderWriterLockSlim mLock;
|
||||
|
||||
public SafeReadHandle(ReaderWriterLockSlim mLock)
|
||||
{
|
||||
this.mLock = mLock;
|
||||
mLock.EnterReadLock();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (mDisposed)
|
||||
|
@ -66,5 +76,4 @@ namespace BattleBitAPI.Common.Threading
|
|||
|
||||
mLock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +1,11 @@
|
|||
namespace BattleBitAPI.Networking
|
||||
namespace BattleBitAPI.Networking;
|
||||
|
||||
public enum NetworkCommuncation : byte
|
||||
{
|
||||
public enum NetworkCommuncation : byte
|
||||
{
|
||||
//Do not use
|
||||
None = 0,
|
||||
|
||||
Hail = 1,
|
||||
Accepted = 2,
|
||||
Denied = 3,
|
||||
|
||||
}
|
||||
Denied = 3
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
#region
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace CommunityServerAPI.BattleBitAPI.Packets;
|
||||
|
||||
public abstract class BasePacket
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempt to write this packet to the provided stream.
|
||||
/// Return true if the write was successful.
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <returns></returns>
|
||||
public abstract bool TryWrite(Stream destination);
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
#region
|
||||
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Networking;
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace CommunityServerAPI.BattleBitAPI.Packets;
|
||||
|
||||
public class HailPacket : BasePacket
|
||||
{
|
||||
public byte CurrentPlayers;
|
||||
public MapDayNight DayNight;
|
||||
public string Gamemode;
|
||||
|
||||
public ushort GamePort;
|
||||
public byte InQueuePlayers;
|
||||
public bool IsPasswordProtected;
|
||||
public string LoadingScreenText;
|
||||
public string Map;
|
||||
public MapSize MapSize;
|
||||
public byte MaxPlayers;
|
||||
public string ServerName;
|
||||
public string ServerRulesText;
|
||||
|
||||
public override bool TryWrite(Stream destination)
|
||||
{
|
||||
destination.Write((byte)NetworkCommuncation.Hail);
|
||||
destination.Write((ushort)GamePort);
|
||||
destination.Write(IsPasswordProtected);
|
||||
destination.Write(ServerName);
|
||||
destination.Write(Gamemode);
|
||||
destination.Write(Map);
|
||||
destination.Write((byte)MapSize);
|
||||
destination.Write((byte)DayNight);
|
||||
destination.Write((byte)CurrentPlayers);
|
||||
destination.Write((byte)InQueuePlayers);
|
||||
destination.Write((byte)MaxPlayers);
|
||||
destination.Write(LoadingScreenText);
|
||||
destination.Write(ServerRulesText);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -1,14 +1,75 @@
|
|||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Common.Extentions;
|
||||
using BattleBitAPI.Networking;
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
#region
|
||||
|
||||
namespace BattleBitAPI.Server
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Networking;
|
||||
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
using CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BattleBitAPI.Server;
|
||||
|
||||
public class GameServer
|
||||
{
|
||||
public class GameServer
|
||||
// ---- Private Variables ----
|
||||
private byte[] mKeepAliveBuffer;
|
||||
private long mLastPackageReceived;
|
||||
private long mLastPackageSent;
|
||||
private uint mReadPackageSize;
|
||||
private Stream mReadStream;
|
||||
private Stream mWriteStream;
|
||||
|
||||
// ---- Constrction ----
|
||||
public GameServer(TcpClient socket, IPAddress iP, int port, bool isPasswordProtected, string serverName, string gamemode, string map, MapSize mapSize, MapDayNight dayNight, int currentPlayers, int inQueuePlayers, int maxPlayers, string loadingScreenText, string serverRulesText)
|
||||
{
|
||||
IsConnected = true;
|
||||
Socket = socket;
|
||||
|
||||
GameIP = iP;
|
||||
GamePort = port;
|
||||
IsPasswordProtected = isPasswordProtected;
|
||||
ServerName = serverName;
|
||||
Gamemode = gamemode;
|
||||
Map = map;
|
||||
MapSize = mapSize;
|
||||
DayNight = dayNight;
|
||||
CurrentPlayers = currentPlayers;
|
||||
InQueuePlayers = inQueuePlayers;
|
||||
MaxPlayers = maxPlayers;
|
||||
LoadingScreenText = loadingScreenText;
|
||||
ServerRulesText = serverRulesText;
|
||||
|
||||
TerminationReason = string.Empty;
|
||||
|
||||
mWriteStream = new Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0
|
||||
};
|
||||
mReadStream = new Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0
|
||||
};
|
||||
mKeepAliveBuffer = new byte[4]
|
||||
{
|
||||
0, 0, 0, 0
|
||||
};
|
||||
|
||||
mLastPackageReceived = Extensions.TickCount;
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
}
|
||||
|
||||
// ---- Public Variables ----
|
||||
public TcpClient Socket { get; private set; }
|
||||
|
||||
|
@ -16,18 +77,31 @@ namespace BattleBitAPI.Server
|
|||
/// Is game server connected to our server?
|
||||
/// </summary>
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
public IPAddress GameIP { get; private set; }
|
||||
|
||||
public int GamePort { get; private set; }
|
||||
|
||||
public bool IsPasswordProtected { get; private set; }
|
||||
|
||||
public string ServerName { get; private set; }
|
||||
|
||||
public string Gamemode { get; private set; }
|
||||
|
||||
public string Map { get; private set; }
|
||||
|
||||
public MapSize MapSize { get; private set; }
|
||||
|
||||
public MapDayNight DayNight { get; private set; }
|
||||
|
||||
public int CurrentPlayers { get; private set; }
|
||||
|
||||
public int InQueuePlayers { get; private set; }
|
||||
|
||||
public int MaxPlayers { get; private set; }
|
||||
|
||||
public string LoadingScreenText { get; private set; }
|
||||
|
||||
public string ServerRulesText { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
|
@ -35,63 +109,10 @@ namespace BattleBitAPI.Server
|
|||
/// </summary>
|
||||
public string TerminationReason { get; private set; }
|
||||
|
||||
// ---- Private Variables ----
|
||||
private byte[] mKeepAliveBuffer;
|
||||
private Common.Serialization.Stream mWriteStream;
|
||||
private Common.Serialization.Stream mReadStream;
|
||||
private uint mReadPackageSize;
|
||||
private long mLastPackageReceived;
|
||||
private long mLastPackageSent;
|
||||
|
||||
// ---- Constrction ----
|
||||
public GameServer(TcpClient socket, IPAddress iP, int port, bool isPasswordProtected, string serverName, string gamemode, string map, MapSize mapSize, MapDayNight dayNight, int currentPlayers, int inQueuePlayers, int maxPlayers, string loadingScreenText, string serverRulesText)
|
||||
{
|
||||
this.IsConnected = true;
|
||||
this.Socket = socket;
|
||||
|
||||
this.GameIP = iP;
|
||||
this.GamePort = port;
|
||||
this.IsPasswordProtected = isPasswordProtected;
|
||||
this.ServerName = serverName;
|
||||
this.Gamemode = gamemode;
|
||||
this.Map = map;
|
||||
this.MapSize = mapSize;
|
||||
this.DayNight = dayNight;
|
||||
this.CurrentPlayers = currentPlayers;
|
||||
this.InQueuePlayers = inQueuePlayers;
|
||||
this.MaxPlayers = maxPlayers;
|
||||
this.LoadingScreenText = loadingScreenText;
|
||||
this.ServerRulesText = serverRulesText;
|
||||
|
||||
this.TerminationReason = string.Empty;
|
||||
|
||||
this.mWriteStream = new Common.Serialization.Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0,
|
||||
};
|
||||
this.mReadStream = new Common.Serialization.Stream()
|
||||
{
|
||||
Buffer = new byte[Const.MaxNetworkPackageSize],
|
||||
InPool = false,
|
||||
ReadPosition = 0,
|
||||
WritePosition = 0,
|
||||
};
|
||||
this.mKeepAliveBuffer = new byte[4]
|
||||
{
|
||||
0,0,0,0,
|
||||
};
|
||||
|
||||
this.mLastPackageReceived = Extentions.TickCount;
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
}
|
||||
|
||||
// ---- Tick ----
|
||||
public async Task Tick()
|
||||
{
|
||||
if (!this.IsConnected)
|
||||
if (!IsConnected)
|
||||
return;
|
||||
|
||||
try
|
||||
|
@ -108,89 +129,85 @@ namespace BattleBitAPI.Server
|
|||
//Read network packages.
|
||||
while (Socket.Available > 0)
|
||||
{
|
||||
this.mLastPackageReceived = Extentions.TickCount;
|
||||
mLastPackageReceived = Extensions.TickCount;
|
||||
|
||||
//Do we know the package size?
|
||||
if (this.mReadPackageSize == 0)
|
||||
if (mReadPackageSize == 0)
|
||||
{
|
||||
const int sizeToRead = 4;
|
||||
int leftSizeToRead = sizeToRead - this.mReadStream.WritePosition;
|
||||
var leftSizeToRead = sizeToRead - mReadStream.WritePosition;
|
||||
|
||||
int read = await networkStream.ReadAsync(this.mReadStream.Buffer, this.mReadStream.WritePosition, leftSizeToRead);
|
||||
var read = await networkStream.ReadAsync(mReadStream.Buffer, mReadStream.WritePosition, leftSizeToRead);
|
||||
if (read <= 0)
|
||||
throw new Exception("Connection was terminated.");
|
||||
|
||||
this.mReadStream.WritePosition += read;
|
||||
mReadStream.WritePosition += read;
|
||||
|
||||
//Did we receive the package?
|
||||
if (this.mReadStream.WritePosition >= 4)
|
||||
if (mReadStream.WritePosition >= 4)
|
||||
{
|
||||
//Read the package size
|
||||
this.mReadPackageSize = this.mReadStream.ReadUInt32();
|
||||
mReadPackageSize = mReadStream.ReadUInt32();
|
||||
|
||||
if (this.mReadPackageSize > Const.MaxNetworkPackageSize)
|
||||
if (mReadPackageSize > Const.MaxNetworkPackageSize)
|
||||
throw new Exception("Incoming package was larger than 'Conts.MaxNetworkPackageSize'");
|
||||
|
||||
//Is this keep alive package?
|
||||
if (this.mReadPackageSize == 0)
|
||||
{
|
||||
if (mReadPackageSize == 0)
|
||||
Console.WriteLine("Keep alive was received.");
|
||||
}
|
||||
|
||||
//Reset the stream.
|
||||
this.mReadStream.Reset();
|
||||
mReadStream.Reset();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int sizeToRead = (int)mReadPackageSize;
|
||||
int leftSizeToRead = sizeToRead - this.mReadStream.WritePosition;
|
||||
var sizeToRead = (int)mReadPackageSize;
|
||||
var leftSizeToRead = sizeToRead - mReadStream.WritePosition;
|
||||
|
||||
int read = await networkStream.ReadAsync(this.mReadStream.Buffer, this.mReadStream.WritePosition, leftSizeToRead);
|
||||
var read = await networkStream.ReadAsync(mReadStream.Buffer, mReadStream.WritePosition, leftSizeToRead);
|
||||
if (read <= 0)
|
||||
throw new Exception("Connection was terminated.");
|
||||
|
||||
this.mReadStream.WritePosition += read;
|
||||
mReadStream.WritePosition += read;
|
||||
|
||||
//Do we have the package?
|
||||
if (this.mReadStream.WritePosition >= mReadPackageSize)
|
||||
if (mReadStream.WritePosition >= mReadPackageSize)
|
||||
{
|
||||
this.mReadPackageSize = 0;
|
||||
mReadPackageSize = 0;
|
||||
|
||||
await mExecutePackage(this.mReadStream);
|
||||
await mExecutePackage(mReadStream);
|
||||
|
||||
//Reset
|
||||
this.mReadStream.Reset();
|
||||
mReadStream.Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Send the network packages.
|
||||
if (this.mWriteStream.WritePosition > 0)
|
||||
if (mWriteStream.WritePosition > 0)
|
||||
lock (mWriteStream)
|
||||
{
|
||||
lock (this.mWriteStream)
|
||||
if (mWriteStream.WritePosition > 0)
|
||||
{
|
||||
if (this.mWriteStream.WritePosition > 0)
|
||||
{
|
||||
networkStream.Write(this.mWriteStream.Buffer, 0, this.mWriteStream.WritePosition);
|
||||
this.mWriteStream.WritePosition = 0;
|
||||
networkStream.Write(mWriteStream.Buffer, 0, mWriteStream.WritePosition);
|
||||
mWriteStream.WritePosition = 0;
|
||||
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
}
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
}
|
||||
}
|
||||
|
||||
//Are we timed out?
|
||||
if ((Extentions.TickCount - this.mLastPackageReceived) > Const.NetworkTimeout)
|
||||
if (Extensions.TickCount - mLastPackageReceived > Const.NetworkTimeout)
|
||||
throw new Exception("Game server timedout.");
|
||||
|
||||
//Send keep alive if needed
|
||||
if ((Extentions.TickCount - this.mLastPackageSent) > Const.NetworkKeepAlive)
|
||||
if (Extensions.TickCount - mLastPackageSent > Const.NetworkKeepAlive)
|
||||
{
|
||||
//Send keep alive.
|
||||
networkStream.Write(this.mKeepAliveBuffer, 0, 4);
|
||||
networkStream.Write(mKeepAliveBuffer, 0, 4);
|
||||
|
||||
this.mLastPackageSent = Extentions.TickCount;
|
||||
mLastPackageSent = Extensions.TickCount;
|
||||
|
||||
Console.WriteLine("Keep alive was sent.");
|
||||
}
|
||||
|
@ -202,25 +219,23 @@ namespace BattleBitAPI.Server
|
|||
}
|
||||
|
||||
// ---- Internal ----
|
||||
private async Task mExecutePackage(Common.Serialization.Stream stream)
|
||||
private async Task mExecutePackage(Stream stream)
|
||||
{
|
||||
var communcation = (NetworkCommuncation)stream.ReadInt8();
|
||||
switch (communcation)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void mClose(string reason)
|
||||
{
|
||||
if (this.IsConnected)
|
||||
if (IsConnected)
|
||||
{
|
||||
this.TerminationReason = reason;
|
||||
this.IsConnected = false;
|
||||
TerminationReason = reason;
|
||||
IsConnected = false;
|
||||
|
||||
this.mWriteStream = null;
|
||||
this.mReadStream = null;
|
||||
}
|
||||
mWriteStream = null;
|
||||
mReadStream = null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,18 +1,35 @@
|
|||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Common.Extentions;
|
||||
using BattleBitAPI.Common.Serialization;
|
||||
using BattleBitAPI.Networking;
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
#region
|
||||
|
||||
namespace BattleBitAPI.Server
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
using BattleBitAPI.Common.Enums;
|
||||
using BattleBitAPI.Networking;
|
||||
|
||||
using CommunityServerAPI.BattleBitAPI;
|
||||
using CommunityServerAPI.BattleBitAPI.Common.Extentions;
|
||||
|
||||
using Stream = BattleBitAPI.Common.Serialization.Stream;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BattleBitAPI.Server;
|
||||
|
||||
public class ServerListener : IDisposable
|
||||
{
|
||||
public class ServerListener : IDisposable
|
||||
// --- Private ---
|
||||
private TcpListener mSocket;
|
||||
|
||||
// --- Construction ---
|
||||
public ServerListener()
|
||||
{
|
||||
}
|
||||
|
||||
// --- Public ---
|
||||
public bool IsListening { get; private set; }
|
||||
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
public int ListeningPort { get; private set; }
|
||||
|
||||
// --- Events ---
|
||||
|
@ -27,35 +44,43 @@ namespace BattleBitAPI.Server
|
|||
/// Fired when a game server connects.
|
||||
/// </summary>
|
||||
public Func<GameServer, Task> OnGameServerConnected { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fired when a game server disconnects. Check (server.TerminationReason) to see the reason.
|
||||
/// </summary>
|
||||
public Func<GameServer, Task> OnGameServerDisconnected { get; set; }
|
||||
|
||||
// --- Private ---
|
||||
private TcpListener mSocket;
|
||||
// --- Disposing ---
|
||||
public void Dispose()
|
||||
{
|
||||
//Already disposed?
|
||||
if (IsDisposed)
|
||||
return;
|
||||
IsDisposed = true;
|
||||
|
||||
// --- Construction ---
|
||||
public ServerListener() { }
|
||||
if (IsListening)
|
||||
Stop();
|
||||
}
|
||||
|
||||
// --- Starting ---
|
||||
public void Start(IPAddress bindIP, int port)
|
||||
{
|
||||
if (this.IsDisposed)
|
||||
throw new ObjectDisposedException(this.GetType().FullName);
|
||||
if (IsDisposed)
|
||||
throw new ObjectDisposedException(GetType().FullName);
|
||||
if (bindIP == null)
|
||||
throw new ArgumentNullException(nameof(bindIP));
|
||||
if (IsListening)
|
||||
throw new Exception("Server is already listening.");
|
||||
|
||||
this.mSocket = new TcpListener(bindIP, port);
|
||||
this.mSocket.Start();
|
||||
mSocket = new TcpListener(bindIP, port);
|
||||
mSocket.Start();
|
||||
|
||||
this.ListeningPort = port;
|
||||
this.IsListening = true;
|
||||
ListeningPort = port;
|
||||
IsListening = true;
|
||||
|
||||
mMainLoop();
|
||||
}
|
||||
|
||||
public void Start(int port)
|
||||
{
|
||||
Start(IPAddress.Loopback, port);
|
||||
|
@ -64,8 +89,8 @@ namespace BattleBitAPI.Server
|
|||
// --- Stopping ---
|
||||
public void Stop()
|
||||
{
|
||||
if (this.IsDisposed)
|
||||
throw new ObjectDisposedException(this.GetType().FullName);
|
||||
if (IsDisposed)
|
||||
throw new ObjectDisposedException(GetType().FullName);
|
||||
if (!IsListening)
|
||||
throw new Exception("Already not running.");
|
||||
|
||||
|
@ -73,11 +98,13 @@ namespace BattleBitAPI.Server
|
|||
{
|
||||
mSocket.Stop();
|
||||
}
|
||||
catch { }
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
this.mSocket = null;
|
||||
this.ListeningPort = 0;
|
||||
this.IsListening = true;
|
||||
mSocket = null;
|
||||
ListeningPort = 0;
|
||||
IsListening = true;
|
||||
}
|
||||
|
||||
// --- Main Loop ---
|
||||
|
@ -89,11 +116,12 @@ namespace BattleBitAPI.Server
|
|||
mInternalOnClientConnecting(client);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task mInternalOnClientConnecting(TcpClient client)
|
||||
{
|
||||
var ip = (client.Client.RemoteEndPoint as IPEndPoint).Address;
|
||||
|
||||
bool allow = true;
|
||||
var allow = true;
|
||||
if (OnGameServerConnecting != null)
|
||||
allow = await OnGameServerConnecting(ip);
|
||||
|
||||
|
@ -107,9 +135,9 @@ namespace BattleBitAPI.Server
|
|||
GameServer server = null;
|
||||
try
|
||||
{
|
||||
using (CancellationTokenSource source = new CancellationTokenSource(Const.HailConnectTimeout))
|
||||
using (var source = new CancellationTokenSource(Const.HailConnectTimeout))
|
||||
{
|
||||
using (var readStream = Common.Serialization.Stream.Get())
|
||||
using (var readStream = Stream.Get())
|
||||
{
|
||||
var networkStream = client.GetStream();
|
||||
|
||||
|
@ -118,7 +146,7 @@ namespace BattleBitAPI.Server
|
|||
readStream.Reset();
|
||||
if (!await networkStream.TryRead(readStream, 1, source.Token))
|
||||
throw new Exception("Unable to read the package type");
|
||||
NetworkCommuncation type = (NetworkCommuncation)readStream.ReadInt8();
|
||||
var type = (NetworkCommuncation)readStream.ReadInt8();
|
||||
if (type != NetworkCommuncation.Hail)
|
||||
throw new Exception("Incoming package wasn't hail.");
|
||||
}
|
||||
|
@ -304,7 +332,7 @@ namespace BattleBitAPI.Server
|
|||
Console.WriteLine(e.Message);
|
||||
|
||||
var networkStream = client.GetStream();
|
||||
using (var pck = BattleBitAPI.Common.Serialization.Stream.Get())
|
||||
using (var pck = Stream.Get())
|
||||
{
|
||||
pck.Write((byte)NetworkCommuncation.Denied);
|
||||
pck.Write(e.Message);
|
||||
|
@ -314,7 +342,9 @@ namespace BattleBitAPI.Server
|
|||
}
|
||||
await networkStream.FlushAsync();
|
||||
}
|
||||
catch { }
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
client.SafeClose();
|
||||
|
@ -332,6 +362,7 @@ namespace BattleBitAPI.Server
|
|||
//Join to main server loop.
|
||||
await mHandleGameServer(server);
|
||||
}
|
||||
|
||||
private async Task mHandleGameServer(GameServer server)
|
||||
{
|
||||
while (server.IsConnected)
|
||||
|
@ -343,17 +374,4 @@ namespace BattleBitAPI.Server
|
|||
if (OnGameServerDisconnected != null)
|
||||
await OnGameServerDisconnected.Invoke(server);
|
||||
}
|
||||
|
||||
// --- Disposing ---
|
||||
public void Dispose()
|
||||
{
|
||||
//Already disposed?
|
||||
if (this.IsDisposed)
|
||||
return;
|
||||
this.IsDisposed = true;
|
||||
|
||||
if (IsListening)
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
}
|
19
Program.cs
19
Program.cs
|
@ -1,14 +1,19 @@
|
|||
using BattleBitAPI.Client;
|
||||
using BattleBitAPI.Server;
|
||||
#region
|
||||
|
||||
using System.Net;
|
||||
|
||||
class Program
|
||||
using BattleBitAPI.Client;
|
||||
using BattleBitAPI.Server;
|
||||
|
||||
#endregion
|
||||
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
if (Console.ReadLine().Contains("h"))
|
||||
{
|
||||
ServerListener server = new ServerListener();
|
||||
var server = new ServerListener();
|
||||
server.OnGameServerConnecting += OnClientConnecting;
|
||||
server.OnGameServerConnected += OnGameServerConnected;
|
||||
server.OnGameServerDisconnected += OnGameServerDisconnected;
|
||||
|
@ -18,7 +23,7 @@ class Program
|
|||
}
|
||||
else
|
||||
{
|
||||
Client c = new Client("127.0.0.1", 29294);
|
||||
var c = new Client("127.0.0.1", 29294);
|
||||
c.ServerName = "Test Server";
|
||||
c.Gamemode = "TDP";
|
||||
c.Map = "DustyDew";
|
||||
|
@ -36,10 +41,12 @@ class Program
|
|||
Console.WriteLine(ip + " is connecting.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static async Task OnGameServerConnected(GameServer server)
|
||||
{
|
||||
Console.WriteLine("Server " + server.ServerName + " was connected.");
|
||||
}
|
||||
|
||||
private static async Task OnGameServerDisconnected(GameServer server)
|
||||
{
|
||||
Console.WriteLine("Server " + server.ServerName + " was disconnected. (" + server.TerminationReason + ")");
|
||||
|
|
Loading…
Reference in New Issue