Ejemplo n.º 1
0
        private void OnRecv(IAsyncResult ar)
        {
            try
            {
                IPEndPoint remoteEndPoint = null;
                byte[]     cache          = udpClient.EndReceive(ar, ref remoteEndPoint);

                Debug.Log("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);
                }
            }
        }