This commit is contained in:
CortexCore
2024-06-08 10:07:40 +08:00
parent ccc9957809
commit b9731c20a1
11 changed files with 231 additions and 44 deletions

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Timers;
using Cysharp.Threading.Tasks;
@@ -38,6 +39,10 @@ namespace BITKit.Net
private readonly GenericEvent _events = new();
private readonly ValidHandle _isConnected = new();
private int _index = 1001;
private readonly ConcurrentDictionary<int, object> _p2p = new();
private readonly ConcurrentDictionary<string,object> _rpc = new();
public KcpNetClient()
{
client = new KcpClient(
@@ -161,6 +166,11 @@ namespace BITKit.Net
case NetCommandType.Ping:
Ping = (int)(DateTime.Now - _lastPingTime).TotalMilliseconds;
break;
case NetCommandType.ReturnToClient:
var id = reader.ReadInt32();
var value = BITBinary.Read(reader);
_p2p.TryAdd(id,value);
break;
default:
BIT4Log.Log<KcpClient>($"未知消息类型:{type},字节:{(byte)type}");
if (bytes.Array != null)
@@ -217,15 +227,36 @@ namespace BITKit.Net
Send(NetCommandType.TargetCommand,id,command);
}
public UniTask<T> GetFromServer<T>(string addressablePath = Constant.System.Internal)
public async UniTask<T> GetFromServer<T>(T command = default)
{
var id = _index++;
using var ms = new MemoryStream();
await using var writer = new BinaryWriter(ms);
writer.Write((byte)NetCommandType.GetFromServer);
writer.Write(id);
BITBinary.Write(writer,command);
var bytes = ms.ToArray();
commandQueue.Enqueue(bytes);
var startTime = DateTime.Now;
while (true)
{
if(DateTime.Now-startTime>TimeSpan.FromSeconds(5) || IsConnected is false)
throw new TimeoutException();
if (_p2p.TryRemove(id, out var value))
{
return (T)value;
}
await Task.Delay(100);
}
}
public UniTask<T> GetFromClient<T>(int id, T command = default)
{
throw new NotImplementedException();
}
public UniTask<T> GetFromClient<T>(int id, string addressablePath = Constant.System.Internal)
{
throw new NotImplementedException();
}
public void AddRpcHandle(object rpcHandle)
{
@@ -237,9 +268,19 @@ namespace BITKit.Net
_events.AddListener<T>(handle);
}
public void AddCommandListener<T>(Func<T, T> func)
{
_rpc.GetOrAdd(typeof(T).FullName, func);
}
public void RemoveCommandListener<T>(Func<T, T> func)
{
_rpc.TryRemove(typeof(T).FullName, out _);
}
public void RemoveCommandListener<T>(Action<T> handle)
{
throw new NotImplementedException();
_events.RemoveListener<T>(handle);
}
public void SendRT(string rpcName, params object[] pars)