protected internal virtual void Update() { if (!_Ready) { return; } // 1, send. if (_Started) { BufferInfo binfo; while (_PendingSendMessages.TryDequeue(out binfo)) { var message = binfo.Buffer; if (binfo.Count > CONST.MTU) { int cnt = binfo.Count; int offset = 0; var buffer = BufferPool.GetBufferFromPool(); while (cnt > CONST.MTU) { Buffer.BlockCopy(message, offset, buffer, 0, CONST.MTU); _KCP.kcp_send(buffer, CONST.MTU); cnt -= CONST.MTU; offset += CONST.MTU; } if (cnt > 0) { Buffer.BlockCopy(message, offset, buffer, 0, cnt); _KCP.kcp_send(buffer, cnt); } BufferPool.ReturnBufferToPool(buffer); } else { _KCP.kcp_send(message, binfo.Count); } if (_OnSendComplete != null) { _OnSendComplete(message, true); } } } // 2, real update. _KCP.kcp_update((uint)Environment.TickCount); // 3, receive if (_Started) { int recvcnt = _KCP.kcp_recv(_RecvBuffer, CONST.MTU); if (_OnReceive != null) { if (recvcnt > 0) { _OnReceive(_RecvBuffer, recvcnt, _Info.EP); } } } }
private void Init(string url, uint conv) { if (conv == 0) { PlatDependant.LogError("KCP conversation id should not be 0."); } _Connection = new UDPClient(url); _Conv = conv; _ConnectionHandle = GCHandle.Alloc(_Connection); _KCP = KCPLib.kcp_create(conv, (IntPtr)_ConnectionHandle); _KCP.kcp_setoutput(Func_KCPOutput); _KCP.kcp_nodelay(1, 10, 2, 1); // set minrto to 10? _Connection.UpdateInterval = 10; _Connection.PreDispose = _con => DisposeSelf(); _Connection.OnReceive = (data, cnt, sender) => _KCP.kcp_input(data, cnt); _Connection.OnSend = (data, cnt) => { if (cnt > CONST.MTU) { int offset = 0; var buffer = BufferPool.GetBufferFromPool(); while (cnt > CONST.MTU) { Buffer.BlockCopy(data, offset, buffer, 0, CONST.MTU); _KCP.kcp_send(buffer, CONST.MTU); cnt -= CONST.MTU; offset += CONST.MTU; } if (cnt > 0) { Buffer.BlockCopy(data, offset, buffer, 0, cnt); _KCP.kcp_send(buffer, cnt); } BufferPool.ReturnBufferToPool(buffer); } else { _KCP.kcp_send(data, cnt); } return(true); }; _Connection.OnUpdate = _con => { _KCP.kcp_update((uint)Environment.TickCount); int recvcnt = _KCP.kcp_recv(_RecvBuffer, CONST.MTU); if (_OnReceive != null) { if (recvcnt > 0) { _OnReceive(_RecvBuffer, recvcnt, _Connection.RemoteEndPoint); } } }; }