SWT: Code formatting and syntax

This commit is contained in:
MrGadget1024 2023-11-20 19:26:09 -05:00
parent 2425898def
commit 36a78fff7e
11 changed files with 61 additions and 66 deletions

View File

@ -9,7 +9,7 @@ public class ClientWebsocketSettingsDrawer : PropertyDrawer
{
readonly string websocketPortOptionName = nameof(ClientWebsocketSettings.ClientPortOption);
readonly string customPortName = nameof(ClientWebsocketSettings.CustomClientPort);
readonly GUIContent portOptionLabel = new ("Client Port Option",
readonly GUIContent portOptionLabel = new("Client Port Option",
"Specify what port the client websocket connection uses (default same as server port)");
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
@ -63,6 +63,7 @@ float SumPropertyHeights(SerializedProperty property, params string[] propertyNa
float totalHeight = 0;
foreach (var name in propertyNames)
totalHeight += EditorGUI.GetPropertyHeight(property.FindPropertyRelative(name)) + EditorGUIUtility.standardVerticalSpacing;
return totalHeight;
}
}

View File

@ -18,6 +18,25 @@ public enum ClientState
/// </summary>
public abstract class SimpleWebClient
{
readonly int maxMessagesPerTick;
protected ClientState state;
protected readonly int maxMessageSize;
protected readonly BufferPool bufferPool;
public readonly ConcurrentQueue<Message> receiveQueue = new ConcurrentQueue<Message>();
public ClientState ConnectionState => state;
public event Action onConnect;
public event Action onDisconnect;
public event Action<ArraySegment<byte>> onData;
public event Action<Exception> onError;
public abstract void Connect(Uri serverAddress);
public abstract void Disconnect();
public abstract void Send(ArraySegment<byte> segment);
public static SimpleWebClient Create(int maxMessageSize, int maxMessagesPerTick, TcpConfig tcpConfig)
{
#if UNITY_WEBGL && !UNITY_EDITOR
@ -27,13 +46,6 @@ public static SimpleWebClient Create(int maxMessageSize, int maxMessagesPerTick,
#endif
}
readonly int maxMessagesPerTick;
protected readonly int maxMessageSize;
public readonly ConcurrentQueue<Message> receiveQueue = new ConcurrentQueue<Message>();
protected readonly BufferPool bufferPool;
protected ClientState state;
protected SimpleWebClient(int maxMessageSize, int maxMessagesPerTick)
{
this.maxMessageSize = maxMessageSize;
@ -41,13 +53,6 @@ protected SimpleWebClient(int maxMessageSize, int maxMessagesPerTick)
bufferPool = new BufferPool(5, 20, maxMessageSize);
}
public ClientState ConnectionState => state;
public event Action onConnect;
public event Action onDisconnect;
public event Action<ArraySegment<byte>> onData;
public event Action<Exception> onError;
/// <summary>
/// Processes all new messages
/// </summary>
@ -92,11 +97,7 @@ public void ProcessMessageQueue(MonoBehaviour behaviour)
}
}
if (receiveQueue.Count > 0)
Debug.LogWarning($"SimpleWebClient ProcessMessageQueue has {receiveQueue.Count} remaining.");
Log.Warn($"SimpleWebClient ProcessMessageQueue has {receiveQueue.Count} remaining.");
}
public abstract void Connect(Uri serverAddress);
public abstract void Disconnect();
public abstract void Send(ArraySegment<byte> segment);
}
}

View File

@ -23,6 +23,18 @@ public class WebSocketClientWebGl : SimpleWebClient
{
static readonly Dictionary<int, WebSocketClientWebGl> instances = new Dictionary<int, WebSocketClientWebGl>();
[MonoPInvokeCallback(typeof(Action<int>))]
static void OpenCallback(int index) => instances[index].onOpen();
[MonoPInvokeCallback(typeof(Action<int>))]
static void CloseCallBack(int index) => instances[index].onClose();
[MonoPInvokeCallback(typeof(Action<int, IntPtr, int>))]
static void MessageCallback(int index, IntPtr bufferPtr, int count) => instances[index].onMessage(bufferPtr, count);
[MonoPInvokeCallback(typeof(Action<int>))]
static void ErrorCallback(int index) => instances[index].onErr();
/// <summary>
/// key for instances sent between c# and js
/// </summary>
@ -37,6 +49,8 @@ public class WebSocketClientWebGl : SimpleWebClient
/// </summary>
Queue<byte[]> ConnectingSendQueue;
public bool CheckJsConnected() => SimpleWebJSLib.IsConnected(index);
internal WebSocketClientWebGl(int maxMessageSize, int maxMessagesPerTick) : base(maxMessageSize, maxMessagesPerTick)
{
#if !UNITY_WEBGL || UNITY_EDITOR
@ -44,8 +58,6 @@ internal WebSocketClientWebGl(int maxMessageSize, int maxMessagesPerTick) : base
#endif
}
public bool CheckJsConnected() => SimpleWebJSLib.IsConnected(index);
public override void Connect(Uri serverAddress)
{
index = SimpleWebJSLib.Connect(serverAddress.ToString(), OpenCallback, CloseCallBack, MessageCallback, ErrorCallback);
@ -72,11 +84,9 @@ public override void Send(ArraySegment<byte> segment)
{
SimpleWebJSLib.Send(index, segment.Array, segment.Offset, segment.Count);
}
else
else if (ConnectingSendQueue == null)
{
if (ConnectingSendQueue == null)
ConnectingSendQueue = new Queue<byte[]>();
ConnectingSendQueue = new Queue<byte[]>();
ConnectingSendQueue.Enqueue(segment.ToArray());
}
}
@ -128,17 +138,5 @@ void onErr()
receiveQueue.Enqueue(new Message(new Exception("Javascript Websocket error")));
Disconnect();
}
[MonoPInvokeCallback(typeof(Action<int>))]
static void OpenCallback(int index) => instances[index].onOpen();
[MonoPInvokeCallback(typeof(Action<int>))]
static void CloseCallBack(int index) => instances[index].onClose();
[MonoPInvokeCallback(typeof(Action<int, IntPtr, int>))]
static void MessageCallback(int index, IntPtr bufferPtr, int count) => instances[index].onMessage(bufferPtr, count);
[MonoPInvokeCallback(typeof(Action<int>))]
static void ErrorCallback(int index) => instances[index].onErr();
}
}

View File

@ -60,7 +60,6 @@ public void Dispose()
Release();
}
public void CopyTo(byte[] target, int offset)
{
if (count > (target.Length + offset))
@ -141,13 +140,13 @@ public void Return(ArrayBuffer buffer)
void IncrementCreated()
{
int next = Interlocked.Increment(ref _current);
// Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}");
Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}");
}
[Conditional("DEBUG")]
void DecrementCreated()
{
int next = Interlocked.Decrement(ref _current);
// Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}");
Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}");
}
}
@ -200,7 +199,6 @@ public BufferPool(int bucketCount, int smallest, int largest)
buckets[i] = new BufferBucket((int)Math.Ceiling(size));
}
Validate();
// Example

View File

@ -10,11 +10,10 @@ namespace Mirror.SimpleWeb
{
internal sealed class Connection : IDisposable
{
readonly object disposedLock = new object();
public const int IdNotSet = -1;
private readonly object disposedLock = new object();
public TcpClient client;
public int connId = IdNotSet;
/// <summary>
@ -28,7 +27,6 @@ internal sealed class Connection : IDisposable
/// </summary>
public string remoteAddress;
public Stream stream;
public Thread receiveThread;
public Thread sendThread;
@ -37,7 +35,7 @@ internal sealed class Connection : IDisposable
public ConcurrentQueue<ArrayBuffer> sendQueue = new ConcurrentQueue<ArrayBuffer>();
public Action<Connection> onDispose;
private volatile bool hasDisposed;
volatile bool hasDisposed;
public Connection(TcpClient client, Action<Connection> onDispose)
{

View File

@ -148,7 +148,6 @@ static void ReadOneMessage(Config config, byte[] buffer)
MessageProcessor.ThrowIfMsgLengthTooLong(totalSize, maxMessageSize);
}
ArrayBuffer msg = bufferPool.Take(totalSize);
msg.count = 0;
while (fragments.Count > 0)
@ -177,14 +176,14 @@ static Header ReadHeader(Config config, byte[] buffer, bool opCodeContinuation =
// read 2
header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.HeaderMinSize);
// log after first blocking call
// Log.Verbose($"[SimpleWebTransport] Message From {conn}");
Log.Verbose($"[SimpleWebTransport] Message From {conn}");
if (MessageProcessor.NeedToReadShortLength(buffer))
header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.ShortLength);
if (MessageProcessor.NeedToReadLongLength(buffer))
header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.LongLength);
// Log.DumpBuffer($"[SimpleWebTransport] Raw Header", buffer, 0, header.offset);
Log.DumpBuffer($"[SimpleWebTransport] Raw Header", buffer, 0, header.offset);
MessageProcessor.ValidateHeader(buffer, maxMessageSize, expectMask, opCodeContinuation);
@ -195,7 +194,7 @@ static Header ReadHeader(Config config, byte[] buffer, bool opCodeContinuation =
header.payloadLength = MessageProcessor.GetPayloadLength(buffer);
header.finished = MessageProcessor.Finished(buffer);
// Log.Verbose($"[SimpleWebTransport] Header ln:{header.payloadLength} op:{header.opcode} mask:{expectMask}");
Log.Verbose($"[SimpleWebTransport] Header ln:{header.payloadLength} op:{header.opcode} mask:{expectMask}");
return header;
}
@ -239,7 +238,7 @@ static void HandleCloseMessage(Config config, byte[] buffer, int msgOffset, int
}
// dump after mask off
// Log.DumpBuffer($"[SimpleWebTransport] Message", buffer, msgOffset, payloadLength);
Log.DumpBuffer($"[SimpleWebTransport] Message", buffer, msgOffset, payloadLength);
Log.Info($"[SimpleWebTransport] Close: {GetCloseCode(buffer, msgOffset)} message:{GetCloseMessage(buffer, msgOffset, payloadLength)}");
conn.Dispose();

View File

@ -9,8 +9,8 @@ namespace Mirror.SimpleWeb
/// </summary>
public class Request
{
private static readonly char[] lineSplitChars = new char[] { '\r', '\n' };
private static readonly char[] headerSplitChars = new char[] { ':' };
static readonly char[] lineSplitChars = new char[] { '\r', '\n' };
static readonly char[] headerSplitChars = new char[] { ':' };
public string RequestLine;
public Dictionary<string, string> Headers = new Dictionary<string, string>();

View File

@ -144,7 +144,7 @@ static int SendMessage(byte[] buffer, int startOffset, ArrayBuffer msg, bool set
offset += msgLength;
// dump before mask on
// Log.DumpBuffer("[SimpleWebTransport] Send", buffer, startOffset, offset);
Log.DumpBuffer("[SimpleWebTransport] Send", buffer, startOffset, offset);
if (setMask)
{

View File

@ -105,9 +105,8 @@ static bool IsGet(byte[] getHeader)
void AcceptHandshake(Stream stream, string msg)
{
using (
ArrayBuffer keyBuffer = bufferPool.Take(KeyLength + Constants.HandshakeGUIDLength),
responseBuffer = bufferPool.Take(ResponseLength))
using (ArrayBuffer keyBuffer = bufferPool.Take(KeyLength + Constants.HandshakeGUIDLength),
responseBuffer = bufferPool.Take(ResponseLength))
{
GetKey(msg, keyBuffer.array);
AppendGuid(keyBuffer.array);

View File

@ -253,7 +253,7 @@ public Request GetClientRequest(int id)
if (!connections.TryGetValue(id, out Connection conn))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[SimpleWebTransport] Cant get request of connection {id} because connection was not found in dictionary.");
Console.WriteLine($"[SimpleWebTransport] Cannot get request of connection {id} because connection was not found in dictionary.");
Console.ResetColor();
return null;
}

View File

@ -14,7 +14,7 @@ public class SimpleWebTransport : Transport, PortTransport
[Tooltip("Port to use for server and client")]
public ushort port = 7778;
public ushort Port { get => port; set => port=value; }
public ushort Port { get => port; set => port = value; }
[Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker might send multiple fake packets with 2GB headers, causing the server to run out of memory after allocating multiple large packets.")]
public int maxMessageSize = 16 * 1024;
@ -127,7 +127,8 @@ public override void ClientConnect(string hostname)
Host = hostname,
};
switch (clientWebsocketSettings.ClientPortOption) {
switch (clientWebsocketSettings.ClientPortOption)
{
case WebsocketPortOption.SpecifyPort:
builder.Port = clientWebsocketSettings.CustomClientPort;
break;
@ -148,7 +149,7 @@ public override void ClientConnect(Uri uri)
// connecting or connected
if (ClientConnected())
{
Debug.LogError("[SimpleWebTransport] Already Connected");
Log.Error("[SimpleWebTransport] Already Connected");
return;
}
@ -187,7 +188,7 @@ public override void ClientSend(ArraySegment<byte> segment, int channelId)
{
if (!ClientConnected())
{
Debug.LogError("[SimpleWebTransport] Not Connected");
Log.Error("[SimpleWebTransport] Not Connected");
return;
}
@ -240,7 +241,7 @@ public override bool ServerActive()
public override void ServerStart()
{
if (ServerActive())
Debug.LogError("[SimpleWebTransport] Server Already Started");
Log.Error("[SimpleWebTransport] Server Already Started");
SslConfig config = SslConfigLoader.Load(sslEnabled, sslCertJson, sslProtocols);
server = new SimpleWebServer(serverMaxMessagesPerTick, TcpConfig, maxMessageSize, handshakeMaxSize, config);
@ -259,7 +260,7 @@ public override void ServerStart()
public override void ServerStop()
{
if (!ServerActive())
Debug.LogError("[SimpleWebTransport] Server Not Active");
Log.Error("[SimpleWebTransport] Server Not Active");
server.Stop();
server = null;
@ -268,7 +269,7 @@ public override void ServerStop()
public override void ServerDisconnect(int connectionId)
{
if (!ServerActive())
Debug.LogError("[SimpleWebTransport] Server Not Active");
Log.Error("[SimpleWebTransport] Server Not Active");
server.KickClient(connectionId);
}