/// <summary> /// KCP信道 /// </summary> /// <param name="conv">会话id</param> /// <param name="udpClient">下层协议</param> /// <param name="remoteEndPoint">远程端点</param> public KChannel(uint conv, UdpClient udpClient, IPEndPoint remoteEndPoint) { this.conv = conv; this.udpClient = udpClient; this.remoteEndPoint = remoteEndPoint; this.createTime = (uint)SystemTime.ClientNow(); kcp = new KCP(conv, KcpOutput); kcp.NoDelay(1, 10, 1, 1); kcp.WndSize(256, 256); kcp.SetMtu(470); }
/// <summary> /// 处理接收到的数据 /// </summary> /// <param name="cache"> 接收到的数据</param> public void HandleRecv(byte[] cache) { if (this.disposed) { return; } kcp.Input(cache); while (true) { try { if (this.disposed) { return; } int size = kcp.PeekSize(); if (size < 0) { return; } if (size == 0) { //发生错误,应该断开 this.OnError((ErrorCode)SocketError.NetworkReset); this.Dispose(); return; } if (!isConnected) { this.isConnected = true; } var buffer = new byte[size]; kcp.Recv(buffer); this.lastRecvTime = (uint)SystemTime.ClientNow(); this.OnRead(buffer); } catch (Exception e) { Debug.LogError(e); } } }
public void Update() { if (disposed) { return; } uint timeNow = (uint)SystemTime.ClientNow(); try { kcp.Update(timeNow); } catch (Exception) { //网络无法访问 this.OnError(ErrorCode.ERR_SocketError); return; } if (!isConnected) { // 没连接上则报错 if (timeNow - this.createTime > 3 * 1000) { this.OnError(ErrorCode.ERR_KcpCantConnect); this.Dispose(); return; } } else { //因是异步接收,lastRecvTime有可能比timeNow刷新慢。 if (timeNow < this.lastRecvTime) { return; } // 超时断开连接 if ((timeNow - this.lastRecvTime) > 10 * 1000) { Debug.LogError($"{Name} timeNow:{timeNow} lastRecvTime:{lastRecvTime} ts:{(timeNow - this.lastRecvTime)}"); this.OnError(ErrorCode.ERR_KcpChannelTimeout); this.Dispose(); return; } } }