This commit is contained in:
CortexCore
2024-03-31 23:31:00 +08:00
parent e179d2eb53
commit b7b89ee71a
641 changed files with 31286 additions and 22134 deletions

View File

@@ -19,18 +19,24 @@ namespace BITKit.Net
public event Action OnDisconnected;
public event Action OnConnectedFailed;
public bool IsConnected => client.connected;
public int Ping => -1;
public bool ManualTick { get; set; }
public int Ping { get; private set; }
public int Id { get; private set; } = -1;
private readonly KcpClient client;
private readonly Queue<byte[]> commandQueue = new();
private DateTime _lastPingTime = DateTime.Now;
private readonly Timer _timer = new(100)
{
AutoReset = true
};
private readonly GenericEvent _events = new();
public KcpNetClient()
{
client = new KcpClient(
@@ -50,15 +56,8 @@ namespace BITKit.Net
private void Tick(object sender, ElapsedEventArgs e)
{
//await UniTask.SwitchToThreadPool();
while (commandQueue.TryDequeue(out var bytes))
{
client.Send(bytes, KcpChannel.Reliable);
}
//for (var i = 0; i < 32; i++)
{
client.Tick();
}
if (!ManualTick)
Tick();
}
public async void Disconnect()
@@ -145,6 +144,9 @@ namespace BITKit.Net
case NetCommandType.Heartbeat:
client.Send(new[] { (byte)NetCommandType.Heartbeat }, KcpChannel.Reliable);
break;
case NetCommandType.Ping:
Ping = (int)(DateTime.Now - _lastPingTime).TotalMilliseconds;
break;
default:
BIT4Log.Log<KcpClient>($"未知消息类型:{type},字节:{(byte)type}");
if (bytes.Array != null)
@@ -250,7 +252,29 @@ namespace BITKit.Net
client.Send(bytes, KcpChannel.Reliable);
}
public void Tick() => client.Tick();
#if UNITY_EDITOR
private readonly IntervalUpdate _pingInterval = new(1);
#endif
public void Tick()
{
while (commandQueue.TryDequeue(out var bytes))
{
client.Send(bytes, KcpChannel.Reliable);
}
#if UNITY_EDITOR
if (_pingInterval.AllowUpdate)
{
_lastPingTime = DateTime.Now;
client.Send(new[] { (byte)NetCommandType.Ping }, KcpChannel.Reliable);
}
#endif
client.Tick();
}
public void HandShake()
{
// send client to server