BITKit/Packages/Runtime~/Core/Kcp/KcpNetClient.cs

135 lines
3.8 KiB
C#

using System;
using Cysharp.Threading.Tasks;
using kcp2k;
namespace BITKit.Net
{
public class KcpNetClient:INetClient,INetProvider
{
public event Action OnStartConnect;
public event Action OnConnected;
public event Action OnDisconnected;
public event Action OnConnectedFailed;
public bool IsConnected => client.connected;
public int Ping => 1;
public int Id => 1;
private readonly KcpClient client;
public KcpNetClient()
{
client = new KcpClient(
OnConnectedInternal,
OnData,
OnDisconnectInternal,
OnError,
KCPNet.Config
);
}
public void Disconnect()
{
client.Disconnect();
OnDisconnected?.Invoke();
}
public async UniTask<bool> Connect(string address = "localhost", ushort port = 27014)
{
await UniTask.SwitchToThreadPool();
try
{
client.Connect(address, port);
OnConnected?.Invoke();
return true;
}
catch (Exception e)
{
BIT4Log.LogException(e);
OnConnectedFailed?.Invoke();
return false;
}
}
private void OnData(ArraySegment<byte> bytes, KcpChannel channel)
{
var command = BITBinary.ReadAsValue(bytes.ToArray());
BIT4Log.Log<KCPNetServer>($"已收到指令:command");
}
private void OnConnectedInternal()
{
OnConnected?.Invoke();;
BIT4Log.Log<KcpNetClient>("已连接");
}
private void OnDisconnectInternal()
{
OnDisconnected?.Invoke();
BIT4Log.Log<KcpNetClient>("断开连接");
}
private void OnError(ErrorCode errorCode, string message)
{
BIT4Log.Log<KCPNetServer>($"异常:{errorCode},{message}");
}
public void ServerCommand<T>(T command = default)
{
Send(NetCommandType.Command,command);
}
public void RpcClientCommand<T>(T command = default)
{
Send(NetCommandType.AllClientCommand,command);
}
public void ClientCommand<T>(int id, T command)
{
Send(NetCommandType.TargetCommand,id,command);
}
public UniTask<T> GetFromServer<T>(string addressablePath = Constant.System.Internal)
{
throw new NotImplementedException();
}
public UniTask<T> GetFromClient<T>(int id, string addressablePath = Constant.System.Internal)
{
throw new NotImplementedException();
}
public void AddRpcHandle(object rpcHandle)
{
throw new NotImplementedException();
}
public void AddCommandListener<T>(Action<T> handle)
{
throw new NotImplementedException();
}
public void RemoveCommandListener<T>(Action<T> handle)
{
throw new NotImplementedException();
}
public void SendRT(string rpcName, params object[] pars)
{
throw new NotImplementedException();
}
public void SendTargetRT(int id, string rpcName, params object[] pars)
{
throw new NotImplementedException();
}
public void SendAllRT(string rpcName, params object[] pars)
{
throw new NotImplementedException();
}
private void Send(NetCommandType commandType,params object[] values)
{
var bytes = BinaryBuilder
.Create()
.Write((byte)NetCommandType.TargetCommand)
.Write(values)
.Build();
client.Send(bytes, KcpChannel.Reliable);
}
}
}