This commit is contained in:
CortexCore
2023-06-05 16:25:06 +08:00
parent 9027120bb8
commit 4565ff2e35
2947 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System.Text;
using UnityEngine.Networking;
using System.Threading;
namespace BITKit
{
public class NetworkCore
{
static Dictionary<string, int> counter = new();
[RuntimeInitializeOnLoadMethod]
static void Reload()
{
counter.Clear();
}
[BITCommand]
public static async void NetworkStatus()
{
await UniTask.SwitchToMainThread();
StringBuilder stringBuilder = new();
foreach (var count in counter)
{
stringBuilder.Append($"URL:{count.Key}\tCount:{count.Value}");
}
Debug.Log(stringBuilder);
}
public static void Add(string url)
{
counter.Set(url, counter.Get(url) + 1);
}
}
}

View File

@@ -0,0 +1,80 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
using Cysharp.Threading.Tasks;
using BITKit.HttpNet.Model;
using Sirenix.OdinInspector;
using System.Linq;
namespace BITKit.HttpNet
{
public class NetworkListener : SerializedMonoBehaviour
{
public int port = 7001;
public Provider output;
HttpListener listener = new();
bool isEnabled;
void OnEnable()
{
isEnabled = true;
}
void OnDisable()
{
isEnabled = false;
listener.Stop();
}
void Start()
{
Excute();
}
async void Excute()
{
if (!HttpListener.IsSupported)
{
Debug.Log("HttpListener is not supported this platform");
return;
}
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Prefixes.Add($"http://+:{port}/");
var ticker = await DI.GetAsync<IThreadTicker>();
ticker.Add(Listen);
}
void Listen()
{
listener.Start();
while (isEnabled)
{
var result = listener.BeginGetContext(ListenerCallback, listener);
result.AsyncWaitHandle.WaitOne();
}
}
private void ListenerCallback(IAsyncResult result)
{
var context = listener.EndGetContext(result);
var request = context.Request;
var response = context.Response;
var output = response.OutputStream;
var responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
try
{
this.output?.Set(request);
responseString = BITModel.ContextModel.Get("success");
}
catch (System.Exception e)
{
responseString = BITModel.ContextModel.Error(e);
Debug.LogError(e);
}
var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer);
output.Close();
response.Close();
}
}
}

View File

@@ -0,0 +1,11 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit.HttpNet.Model
{
public record Success
{
public int code = 200;
public string message = "success";
}
}

View File

@@ -0,0 +1,75 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Threading;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Net.Http;
using UnityEngine.UIElements;
using System.Text;
using System.Linq;
using BITKit.HttpNet;
namespace BITKit
{
public class NetworkPost : Provider, ICustomInspector
{
[SubclassSelector, SerializeReference] public References _url;
[SubclassSelector, SerializeReference] public WebProvider webProvider;
public string result;
public int postCount;
public int resultCount;
public string content;
public VisualTreeAsset customTreeAsset;
public VisualTreeAsset GetCustomTreeAsset() => customTreeAsset;
StringBuilder stringBuilder = new();
LimitTimes limitTimes = new();
public override async void Set<T>(T obj)
{
switch (obj)
{
case WWWForm formFields:
if (limitTimes)
{
try
{
NetworkCore.Add(_url);
postCount++;
result = await webProvider.PostAsync(_url, formFields);
resultCount++;
limitTimes.Release();
content = JsonConvert.SerializeObject(formFields);
}
catch (System.Exception e)
{
if (e is not OperationCanceledException or TimeoutException)
{
Debug.LogException(e, this);
}
limitTimes.Release();
}
}
break;
case string _string:
break;
}
}
public VisualElement GetVisualElement() => customTreeAsset?.CloneTree();
}
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(NetworkPost))]
public class NetworkPostInspector : BITInspector<NetworkPost>
{
}
#endif
}

View File

@@ -0,0 +1,168 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System;
using System.Text;
using System.Threading;
using System.Net.Http;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UIElements;
namespace BITKit.HttpNet
{
public class NetworkRequest : BITBehavior, IAction
{
[SubclassSelector, SerializeReference] public References _url;
public Provider onException;
public Provider provider;
public Provider onPing;
public IntervalUpdate updater = new();
[SubclassSelector, SerializeReference] public WebProvider webProvider;
public Counter counter = new();
public string result;
public int requestCount;
public int responsedCount;
public float deltaTick;
public double requestTime;
public LimitTimes limit = new(64);
System.Timers.Timer timer = new();
CompletionRate completionRate = new();
ValidHandle isActive = new();
float internalTime;
CancellationToken cancellationToken;
void Awake()
{
cancellationToken = gameObject.GetCancellationTokenOnDestroy();
timer.Elapsed += (x, y) => OnUpdate();
isActive.AddListener(Set);
isActive.AddDisableElements(this);
#if UNITY_EDITOR
object pause = new();
UnityEditor.EditorApplication.pauseStateChanged += (x) =>
{
isActive.SetDisableElements(pause, x is UnityEditor.PauseState.Paused);
};
updater.onSetActive += SetIntervalUpdateActive;
#endif
}
void OnEnable()
{
isActive.AddElement(this);
}
void Start()
{
isActive.RemoveDisableElements(this);
}
void OnDisable()
{
isActive.RemoveElement(this);
}
void OnDestroy()
{
timer.Dispose();
}
void SetIntervalUpdateActive(bool active)
{
isActive.SetDisableElements(internalTime, active is false);
}
void Update()
{
deltaTick = completionRate;
}
void Set(bool active)
{
if (timer.Enabled != active)
{
if (active)
{
var interval = TimeSpan.FromSeconds(updater.updateInterval).TotalMilliseconds;
timer.Interval = interval;
timer.AutoReset = true;
timer.Start();
}
else
{
timer.Stop();
}
}
}
protected virtual void OnUpdate()
{
try
{
if (limit && updater.enable)
{
Excute(true);
}
}
catch (System.Exception e)
{
BIT4Log.Warnning(e);
throw;
}
}
public void Excute()
{
Excute(false);
}
public async void Excute(bool release = false)
{
BITAppForUnity.ThrowIfNotPlaying();
NetworkCore.Add(_url);
requestCount++;
internalTime += Utility.Time.deltaTime;
completionRate.Get();
var time = Utility.Time.timeAsDouble;
try
{
var result = await webProvider.GetAsync(_url, cancellationToken);
responsedCount++;
provider?.Set(result);
completionRate.Release();
requestTime = Utility.Time.timeAsDouble - time;
if (requestTime is not 0)
onPing?.Set(((int)(requestTime * 1000)).ToString());
this.result = result;
}
catch (System.Exception e)
{
onException?.Set(e);
switch (e)
{
case TimeoutException:
case OperationCanceledException:
case System.Net.WebException:
case System.Net.Http.HttpRequestException:
break;
case InvalidOperationException operationException:
Debug.LogWarning(_url.Get());
goto default;
default:
Debug.LogException(e, this);
break;
}
}
if (release)
{
limit.Release();
}
}
}
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(NetworkRequest))]
public class Inspector : BITInspector<NetworkRequest>
{
public override VisualElement CreateInspectorGUI()
{
var root = base.CreateInspectorGUI();
var button = new Button(agent.Excute);
button.text = "Request";
root.Add(button);
return root;
}
}
#endif
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Sirenix.OdinInspector;
using System.Reflection;
namespace BITKit
{
public class TypeToJson : SerializedMonoBehaviour
{
public Type[] types;
public MethodInfo[] methodInfos;
[ReadOnly] public Type[] deserializeTypes;
[ReadOnly] public MemberInfo[] deserializeMethodInfos;
[Button]
public string ToJson()
{
return JsonConvert.SerializeObject(types);
}
[Button]
public void ToTypes(string json)
{
deserializeTypes = JsonConvert.DeserializeObject<Type[]>(json);
}
[Button]
public string MethodInfosToJson()
{
return JsonConvert.SerializeObject(methodInfos);
}
[Button]
public void JsonToMethodInfos(string json)
{
deserializeMethodInfos = JsonConvert.DeserializeObject<MemberInfo[]>(json);
}
[Button]
public string GetDateTimeJson()
{
return JsonConvert.SerializeObject(DateTime.Now.Date);
}
}
}

View File

@@ -0,0 +1,62 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using UnityEngine.Networking;
using System;
using System.Threading;
namespace BITKit.HttpNet
{
[System.Serializable]
public sealed class UnityWebRequest : WebProvider
{
public override async UniTask<string> GetAsync(string url, CancellationToken cancellationToken = default)
{
await UniTask.SwitchToMainThread(cancellationToken);
using (var request = UnityEngine.Networking.UnityWebRequest.Get(url))
{
await request.SendWebRequest();
if (cancellationToken != default)
{
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException();
}
}
if (request.result is UnityEngine.Networking.UnityWebRequest.Result.Success)
{
return request.downloadHandler.text;
}
else
{
var e = (request) switch
{
_ => "HttpError",
};
throw new System.Net.Http.HttpRequestException(e);
}
}
}
public override async UniTask<string> PostAsync<T>(string url, T value, CancellationToken cancellationToken = default)
{
await UniTask.SwitchToMainThread(cancellationToken);
switch (value)
{
case String _string:
using (var request = UnityEngine.Networking.UnityWebRequest.Post(url, _string))
{
await request.SendWebRequest();
return request.downloadHandler.text;
}
case WWWForm _wwwForm:
using (var request = UnityEngine.Networking.UnityWebRequest.Post(url, _wwwForm))
{
await request.SendWebRequest();
return request.downloadHandler.text;
}
default:
throw new NotImplementedException();
}
}
}
}

View File

@@ -0,0 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Http;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
namespace BITKit
{
public class WebRequest
{
HttpClient client = new();
public async UniTask<T> GetJsonAsync<T>(string url)
{
var result = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject<T>(result);
}
public async void PostAsync(string url, string value)
{
await client.PostAsync(url, new StringContent(value));
}
}
}