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 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 bytes, KcpChannel channel) { var command = BITBinary.ReadAsValue(bytes.ToArray()); BIT4Log.Log($"已收到指令:command"); } private void OnConnectedInternal() { OnConnected?.Invoke();; BIT4Log.Log("已连接"); } private void OnDisconnectInternal() { OnDisconnected?.Invoke(); BIT4Log.Log("断开连接"); } private void OnError(ErrorCode errorCode, string message) { BIT4Log.Log($"异常:{errorCode},{message}"); } public void ServerCommand(T command = default) { Send(NetCommandType.Command,command); } public void RpcClientCommand(T command = default) { Send(NetCommandType.AllClientCommand,command); } public void ClientCommand(int id, T command) { Send(NetCommandType.TargetCommand,id,command); } public UniTask GetFromServer(string addressablePath = Constant.System.Internal) { throw new NotImplementedException(); } public UniTask GetFromClient(int id, string addressablePath = Constant.System.Internal) { throw new NotImplementedException(); } public void AddRpcHandle(object rpcHandle) { throw new NotImplementedException(); } public void AddCommandListener(Action handle) { throw new NotImplementedException(); } public void RemoveCommandListener(Action 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); } } }