public void Check() { void Output(byte[] data, int len) { } // setup KCP Kcp kcp = new Kcp(0, Output); // update at time = 1 kcp.Update(1); // check at time = 2 uint next = kcp.Check(2); // check returns 'ts_flush + interval', or in other words, // 'interval' seconds after UPDATE was called. so 1+100 = 101. Assert.That(next, Is.EqualTo(1 + kcp.interval)); }
/// <summary> /// 更新 /// </summary> /// <param name="dt"></param> public void Update(int dt) { // 更新周期10ms 此处次数大于100 则为 1s 无数据跳出 if (noNetDataCount >= 100) { return; } Interlocked.Increment(ref noNetDataCount); var utc = DateTime.UtcNow; lock (m_lock) { if (nextUpdateTime <= utc) { kcp.Update(utc); nextUpdateTime = kcp.Check(utc); } } }
public void Run() { _cancellationTokenSource = new CancellationTokenSource(); //Task.Run(async () => //{ // try // { // while (!_cancellationTokenSource.IsCancellationRequested) // { // _kcp.Update(DateTime.UtcNow); // int len; // while ((len = _kcp.PeekSize()) > 0) // { // var buffer = new byte[len]; // if (_kcp.Recv(buffer) >= 0) // { // OnReceive(buffer); // //handle.Receive(buffer); // } // } // await Task.Delay(5); // } // } // catch (Exception e) // { // e.ToString(); // } //}); //标准顺序是每次调用了 ikcp_update后, //使用 ikcp_check决定下次什么时间点再次调用 ikcp_update, //而如果中途发生了 ikcp_send, ikcp_input 的话,在下一轮 interval 立马调用 ikcp_update和 ikcp_check。 //使用该方法,原来在处理2000个 kcp连接且每 个连接每10ms调用一次update,改为 check机制后,cpu从 60%降低到 15%。 //_kcp.Update(DateTime.UtcNow); //var nextTime = _kcp.Check(DateTime.UtcNow); _mainTask = Task.Run(async() => { try { DateTime lastTime = DateTime.UtcNow; DateTime nextTime = DateTime.UtcNow; DateTime lastPong = DateTime.UtcNow; while (!_cancellationTokenSource.IsCancellationRequested) { var now = DateTime.UtcNow; if (_needUpdate || (lastTime < nextTime && now > nextTime)) { _needUpdate = false; _kcp.Update(now); int len; while ((len = _kcp.PeekSize()) > 0) { var buffer = new byte[len]; if (_kcp.Recv(buffer) >= 0) { OnReceive(buffer); } lastPong = now; } nextTime = _kcp.Check(now); lastTime = now; } //断线检查 if ((now - lastPong).TotalSeconds > 5) { OnClosed(); break; } await Task.Delay(5); } } catch (Exception e) { e.ToString(); } }); }
private void OnTick() { kcp.Update(current()); var nextUpdate = kcp.Check(current()); var nexttimespan = nextUpdate - current(); }