Exemplo n.º 1
0
        /// <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);
        }
Exemplo n.º 2
0
        private void OnRecv(IAsyncResult ar)
        {
            try
            {
                IPEndPoint remoteEndPoint = null;
                byte[]     cache          = udpClient.EndReceive(ar, ref remoteEndPoint);

                //Debug.LogError("udp recv:" + cache.Length);
                // 长度小于KCP.IKCP_OVERHEAD,不是kcp消息
                if (cache.Length < KCP.IKCP_OVERHEAD)
                {
                    udpClient.BeginReceive(OnRecv, null);
                    return;
                }

                uint conv = 0;
                KCP.ikcp_decode32u(cache, 0, ref conv);

                lock (syncRoot)
                {
                    if (!channels.TryGetValue(conv, out KChannel channel))
                    {
                        //Debug.LogError("recv:" + remoteEndPoint);
                        channel = new KChannel(conv, udpClient, remoteEndPoint)
                        {
                            Name            = "Server",
                            OnReadCallback  = this.OnReadCallback,
                            OnErrorCallback = this.OnErrorCallback
                        };
                        channels.Add(conv, channel);
                    }

                    channel.HandleRecv(cache);
                }

                udpClient.BeginReceive(OnRecv, null);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e);

                if (udpClient != null)
                {
                    //异常引发可能是远端强制关闭,服务端需继续拉起接收
                    udpClient.BeginReceive(OnRecv, null);
                }
            }
        }