예제 #1
0
    //void process_connect_packet()
    //{
    //    mRecvQueue.Switch();

    //    if (!mRecvQueue.Empty())
    //    {
    //        var buf = mRecvQueue.Pop();

    //        //UInt32 conv = 1;
    //        //KCP.ikcp_decode32u(buf, 0, ref conv);

    //        //if (conv <= 0)
    //        //    throw new Exception("inlvaid connect back packet");

    //        //init_kcp(conv);

    //        //mInConnectStage = false;
    //        //mConnectSucceed = true;

    //        //m_connectStatusCallback(NetworkState.Connected);
    //        //evHandler(cliEvent.Connected, null, null);
    //    }
    //}

    void process_recv_queue(UInt32 current)
    {
        mRecvQueue.Switch();

        while (!mRecvQueue.Empty())
        {
           
            var buf = mRecvQueue.Pop();
          
           int input= mKcp.Input(buf);
            mNeedUpdateFlag = true;
            //mKcp.Update(current);
            //Debug.Log("process_recv_queue :" + buf.Length + "  input:"+ input+" PeekSize:" + mKcp.PeekSize());
            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                var buffer = new byte[size];
                if (mKcp.Recv(buffer) > 0)
                {
                    int offset = 0;
                    //Debug.Log("m_byteCallBack ---------");
                    m_byteCallBack(buffer, ref offset, buffer.Length);
                }
            }
        }
    }
예제 #2
0
파일: KCPSession.cs 프로젝트: zj831007/SGF
        private void DoReceiveInMain()
        {
            m_RecvBufQueue.Switch();

            while (!m_RecvBufQueue.Empty())
            {
                var recvBufferRaw = m_RecvBufQueue.Pop();
                int ret           = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);

                //收到的不是一个正确的KCP包
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包!Ret:{0}", ret);
                    return;
                }

                m_NeedKcpUpdateFlag = true;

                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (m_Kcp.Recv(recvBuffer) > 0)
                    {
                        NetMessage msg = new NetMessage();
                        msg.Deserialize(recvBuffer, size);

                        m_listener.OnReceive(this, msg);
                    }
                }
            }
        }
예제 #3
0
        private void DoReceiveInMain()
        {
            recvBuffQueue.Switch();
            while (!recvBuffQueue.Empty())
            {
                var recvBufferRaw = recvBuffQueue.Pop();
                int ret           = kcp.Input(recvBufferRaw, recvBufferRaw.Length);

                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包, Ret:{0}", ret);
                    return;
                }

                needKcpUpdateFlag = true;
                for (int size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (kcp.Recv(recvBuffer) > 0)
                    {
                        lastRecvTimestamp = (uint)TimeUtility.GetTotalMillisecondsSince1970();
                        var data = ProtoBuffUtility.Deserialize <FSPDataSToC>(recvBuffer);
                        recvListener?.Invoke(data.frame);
                    }
                }
            }
        }
예제 #4
0
        private void DoReceiveInMain()
        {
            recvBufQueue.Switch();

            while (!recvBufQueue.Empty())
            {
                var recvBufferRaw = recvBufQueue.Pop();
                int ret           = kcp.Input(recvBufferRaw, recvBufferRaw.Length);
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包!Ret:{0}", ret);
                    return;
                }
                needKcpUpdateFlag = true;

                for (int size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (kcp.Recv(recvBuffer) > 0)
                    {
                        listener.OnReceive(this, recvBuffer, size);
                    }
                }
            }
        }
예제 #5
0
    public static void Update()
    {
        if (!Connected)
        {
            return;
        }

        if (WillDisconnect)
        {
            Disconnect();
            WillDisconnect = false;

            return;
        }

        UpdateTime += FrameReplay.deltaTime;
        Kcp.Update((uint)Mathf.FloorToInt(UpdateTime * 1000));

        for (var size = Kcp.PeekSize(); size > 0; size = Kcp.PeekSize())
        {
            var buffer = new byte[size];
            int n      = Kcp.Recv(buffer);
            if (n > 0)
            {
                PacketProxy.SetBuffer(buffer);
                PacketProxy.Analysis(n, Packet);
            }
        }
    }
예제 #6
0
        private void HandleRecvQueue()
        {
            recvQueue.Switch();
            while (!recvQueue.Empty())
            {
                var recvBufferRaw = recvQueue.Pop();
                int ret           = kcpObject.Input(recvBufferRaw, recvBufferRaw.Length);

                //收到的不是一个正确的KCP包
                if (ret < 0)
                {
                    string str = System.Text.Encoding.UTF8.GetString(recvBufferRaw, 0, recvBufferRaw.Length);
                    DLog.LogFormat("收到了错误的kcp包: {0}", str);
                    return;
                }

                needKcpUpdateFlag = true;

                for (int size = kcpObject.PeekSize(); size > 0; size = kcpObject.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    int treclen    = kcpObject.Recv(recvBuffer, recvBuffer.Length);
                    if (treclen > 0)
                    {
                        PushRecData(recvBuffer, treclen);
                    }
                }
            }
        }
예제 #7
0
        private void Update()
        {
            while (true)
            {
                if (_receiveMeesages.Count > 0)
                {
                    var buf = _receiveMeesages.Dequeue();

                    _kcp.Input(buf);
                    // mNeedUpdateFlag = true;

                    for (var size = _kcp.PeekSize(); size > 0; size = _kcp.PeekSize())
                    {
                        var buffer = new byte[size];
                        if (_kcp.Recv(buffer) > 0)
                        {
                            _reveiveHandler(buffer);
                        }
                    }
                }

                _kcp.Update(iclock());
                Thread.Sleep(10);
            }
        }
예제 #8
0
        private void DoReceiveInMain()
        {
            recvBufQueue.Switch();
            while (!recvBufQueue.Empty())
            {
                var recvBufferRaw = recvBufQueue.Pop();
                int ret           = kcp.Input(recvBufferRaw, recvBufferRaw.Length);
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包!Ret:{0}", ret);
                    return;
                }

                needKcpUpdateFlag = true;

                for (int size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (kcp.Recv(recvBuffer) > 0)
                    {
                        if (listener != null)
                        {
                            FSPDataCToS data = ProtoBuffUtility.Deserialize <FSPDataCToS>(recvBuffer);
                            listener(data);
                        }
                        else
                        {
                            Debuger.LogError("找不到接收者!");
                        }
                    }
                }
            }
        }
예제 #9
0
        public int ReceiveData(byte[] ar)
        {
            if (needSwitchRecvQueue)
            {
                needSwitchRecvQueue = false;
                mRecvQueue.Switch();
                while (!mRecvQueue.Empty())
                {
                    var buf = mRecvQueue.Pop();

                    mKcp.Input(buf);
                    mNeedUpdateFlag = true;
                }
            }

            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                int recvSize = mKcp.Recv(ar);
                if (recvSize > 0)
                {
                    return(recvSize);
                }
            }
            needSwitchRecvQueue = true;
            return(0);
        }
예제 #10
0
    void HandleRecvQueue()
    {
        if (_kcpQueue.Count <= 0)
        {
            return;
        }

        List <byte[]> kcpData = new List <byte[]>();

        lock (_kcpQueue) {
            while (_kcpQueue.Count > 0)
            {
                kcpData.Add(_kcpQueue.Dequeue());
            }
        }
        foreach (byte[] data in kcpData)
        {
            int ret = _kcp.Input(data);
            // invalid kcp package
            if (ret < 0)
            {
                continue;
            }
            for (int size = _kcp.PeekSize(); size > 0; size = _kcp.PeekSize())
            {
                var recvBuffer = new byte[size];
                if (_kcp.Recv(recvBuffer) > 0)
                {
                    _queue.Enqueue(recvBuffer);
                }
            }
        }
    }
예제 #11
0
    void process_recv_queue()
    {
        m_RecvQueue.Switch();

        while (!m_RecvQueue.Empty())
        {
            if (m_Kcp == null)
            {//退出
                return;
            }

            var buf = m_RecvQueue.Pop();
            if (this.Status == ClientSessionStatus.InConnect)
            {
                //服务端将返回和握手请求相同的响应数据
                uint _index = 0, _key = 0;
                if (HandshakeUtility.IsHandshakeDataRight(buf, 0, buf.Length, out _index, out _key))
                {
                    if (_index == m_NetIndex && _key == m_Key)
                    {
#if DEBUG
                        Console.WriteLine("连接握手成功");
#endif
                        this.Status = ClientSessionStatus.Connected;
                        var e = Event;
                        if (e != null)
                        {
                            m_LastSendTimestamp = UnityEngine.Time.time;
                            m_LastRecvTimestamp = UnityEngine.Time.time;
                            e(UdpClientEvents.Connected, null);
                        }
                        continue;
                    }
                }
            }

            m_Kcp.Input(buf);
            m_NeedUpdateFlag = true;

            for (var size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
            {
                var buffer = new byte[size];
                if (m_Kcp.Recv(buffer) > 0)
                {
                    m_LastRecvTimestamp = UnityEngine.Time.time;
                    var e = Event;
                    if (e != null)
                    {
                        e(UdpClientEvents.Recv, buffer);
                    }
                }
            }
        }
    }
예제 #12
0
        private void DoReceiveInMain()
        {
            //主线程
            m_RecvBufQueue.Switch();

            while (!m_RecvBufQueue.Empty())
            {
                var recvBufferRaw = m_RecvBufQueue.Pop();
                int ret           = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);

                //收到的不是一个正确的KCP包
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包!Ret:{0}", ret);
                    return;
                }

                m_NeedKcpUpdateFlag = true;

                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (m_Kcp.Recv(recvBuffer) > 0)
                    {
                        NetMessage msg = new NetMessage();
                        msg.Deserialize(recvBuffer, size);


                        if (msg.head.sid == 0)
                        {
                            var errmsg = PBSerializer.NDeserialize <NetErrorMessage>(msg.content);
                            this.LogWarning("服务器返回错误:{0},{1}", errmsg.code, errmsg.info);

                            HandleServerError(errmsg.code);

                            onServerError.InvokeSafe(this, errmsg.code, errmsg.info);
                        }
                        else
                        {
                            //更新SessionId
                            if (Id != msg.head.sid)
                            {
                                Id      = msg.head.sid;
                                LOG_TAG = "KcpConnection[" + Id + "," + m_localPort + "]";
                                this.LogWarning("SessionId发生变化:{0}", Id);
                            }

                            onReceive.InvokeSafe(msg);
                        }
                    }
                }
            }
        }
예제 #13
0
 public void Input(byte[] rcvBuf)
 {
     _kcp.Input(rcvBuf);
     for (var size = _kcp.PeekSize(); size > 0; size = _kcp.PeekSize())
     {
         byte[] buf = new byte[size];
         if (_kcp.Recv(buf) > 0)
         {
             //Log4U.LogDebug("ASynServerKcp:Input Message receive data=", Encoding.ASCII.GetString(buf));
             _recHandler(buf, this);
         }
     }
 }
예제 #14
0
    /// <summary>
    /// 和Update同一个线程调用
    /// </summary>
    internal void process_recv_queue(byte[] datas)
    {
#if DEV
        IRQLog.AppLog.Log(this.m_netIndex.ToString() + ",接收1");
#endif
        if (m_Kcp != null && datas != null)
        {
            m_Kcp.Input(datas);

            m_NeedUpdateFlag = true;

            for (var size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
            {
                byte[] buffer;
                buffer = (UdpLibConfig.UseBytePool ? m_KCPServer.BytePool.Rent(size) : new byte[size]);
                try
                {
                    if (m_Kcp.Recv(buffer) > 0)
                    {
                        m_LastRecvTimestamp = m_KCPServer.m_watch.Elapsed;

                        uint key = 0;
                        KCP.ikcp_decode32u(buffer, 0, ref key);
                        if (m_KCPServer.IsClientKeyCorrect(this.m_netIndex, (int)key) == false)
                        {
#if DEBUG
                            Console.WriteLine("index:{0} key 不对", this.m_netIndex);
#endif
                            m_KCPServer.BytePool.Return(buffer, true);
                            DisposeReason = ClientSessionDisposeReason.IndexKeyError;
                            //key不对
                            Dispose();
                            return;
                        }
#if DEV
                        IRQLog.AppLog.Log(this.m_netIndex.ToString() + ",接收2");
#endif
                        m_KCPServer.OnRecvData(this, buffer, 0, size);
                    }
                }
                finally
                {
                    if (UdpLibConfig.UseBytePool)
                    {
                        m_KCPServer.BytePool.Return(buffer, true);
                    }
                }
            }
        }
    }
예제 #15
0
        private void HandleRecvQueue()
        {
            recvQueue.Switch();
            while (!recvQueue.Empty())
            {
                var recvobject = recvQueue.Pop();
                int ret        = kcpObject.Input(recvobject.bytes, recvobject.length);

                cacheBytesQue.Enqueue(recvobject);

                if (ret < 0)
                {
                    //收到的不是一个正确的KCP包
                    if (IsShowDebugLog)
                    {
                        DLog.Log("Error kcp package.");
                    }
                    return;
                }

                needKcpUpdateFlag = true;

                for (int size = kcpObject.PeekSize(); size > 0; size = kcpObject.PeekSize())
                {
                    if (size > 1048576)
                    {
                        DLog.LogErrorFormat("The size is too long.size = {0}", size);
                    }
                    if (kcpRecvBuffer.Length < size)
                    {
                        int tnewlen = size + kcpRecvBuffer.Length;
                        kcpRecvBuffer = new byte[tnewlen];
                    }
                    else
                    {
                        kcpRecvBuffer.Initialize();
                    }

                    int treclen = kcpObject.Recv(kcpRecvBuffer, size);
                    if (treclen > 0)
                    {
                        PopRecData(kcpRecvBuffer, treclen);
                    }
                }
            }
        }
예제 #16
0
        public void processRecvQueue(SocketAsyncEventArgs e)
        {
            byte[] realData = new byte[e.BytesTransferred];
            Buffer.BlockCopy(e.Buffer, 0, realData, 0, e.BytesTransferred);
            mKcp.Input(realData);

            mNeedUpdateFlag = true;

            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                byte[] buffer = new byte[size];
                if (mKcp.Recv(buffer) > 0)
                {
                    mLastRecvTime = Helper.iclock();
                    RecvDataHandler(this, buffer);
                }
            }
        }
예제 #17
0
        /// <summary>
        /// 将数据Input进Kcp待处理队列
        /// </summary>
        /// <param name="recvBuf"> 接收到的数据</param>
        public void Input(byte[] recvBuf)
        {
            //刷新超时时间
            timer = SystemTime.Clock();

            //将收到的数据打入kcp中处理
            kcp.Input(recvBuf);

            for (var size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
            {
                var buffer = new byte[size];
                if (kcp.Recv(buffer) > 0)
                {
                    //从kcp缓存池中取出排列处理后的数据
                    OnRecive.Invoke(conv, buffer);
                }
            }
        }
예제 #18
0
    private void RecvPendingBuffer()
    {
        int peekSize = 0;

        while ((peekSize = kcp.PeekSize()) > 0)
        {
            byte[] buff = new byte[peekSize];
            kcp.Recv(buff);
            pendingRecvBuffer.Enqueue(buff);
        }
    }
예제 #19
0
        /// <summary>
        /// 执行接收队列
        /// </summary>
        /// <returns>是否需要更新</returns>
        private bool ProcessReceiveQueue()
        {
            receiveQueue.Switch();
            var needUpdate = false;

            while (!receiveQueue.Empty())
            {
                kcp.Input(receiveQueue.Pop());
                needUpdate = true;

                for (var size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
                {
                    var buffer = new byte[size];
                    if (kcp.Recv(buffer) > 0)
                    {
                        Trigger(SocketEvents.Message, buffer);
                    }
                }
            }
            return(needUpdate);
        }
예제 #20
0
    void process_recv_queue()
    {
        mRecvQueue.Switch();

        while (!mRecvQueue.Empty())
        {
            var buf = mRecvQueue.Pop();

            mKcp.Input(buf);
            mNeedUpdateFlag = true;

            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                var buffer = new byte[size];
                if (mKcp.Recv(buffer) > 0)
                {
                    evHandler(buffer);
                }
            }
        }
    }
예제 #21
0
    void process_recv_queue()
    {
        mRecvQueue.Switch();

        while (!mRecvQueue.Empty())
        {
            var buf = mRecvQueue.Pop();

            mKcp.Input(buf);
            mNeedUpdateFlag = true;

            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                var buffer = new byte[size];
                if (mKcp.Recv(buffer) > 0)
                {
                    int offset = 0;
                    m_byteCallBack(buffer, ref offset, buffer.Length);
                }
            }
        }
    }
예제 #22
0
        /// <summary>
        /// 执行接收队列
        /// </summary>
        /// <returns>是否需要更新</returns>
        private bool ProcessReceiveQueue()
        {
            receiveQueue.Switch();
            var needUpdate = false;

            while (!receiveQueue.Empty())
            {
                kcp.Input(receiveQueue.Pop());
                needUpdate = true;

                for (var size = kcp.PeekSize(); size > 0; size = kcp.PeekSize())
                {
                    var buffer = new byte[size];
                    if (kcp.Recv(buffer) > 0)
                    {
                        callback.Invoke(buffer);
                        kcp.Send(buffer);
                    }
                }
            }
            return(needUpdate);
        }
예제 #23
0
 private void ReceiveAsyn(IAsyncResult arg)
 {
     //byte[] rcvBuf = _receiveEP == null ? _socket.Receive(ref _receiveEP) : _socket.EndReceive(arg, ref _receiveEP);
     byte[] rcvBuf = _socket.EndReceive(arg, ref _listenEP);
     if (rcvBuf != null)
     {
         //Log4U.LogDebug("ASynKcpUdpClientSocket:ReceiveAsyn Message receive from ", _listenEP.ToString());
         _kcp.Input(rcvBuf);
         for (var size = _kcp.PeekSize(); size > 0; size = _kcp.PeekSize())
         {
             byte[] buf = new byte[size];
             if (_kcp.Recv(buf) > 0)
             {
                 //Log4U.LogDebug("ASynKcpUdpClientSocket:ReceiveAsyn Message receive data=", Encoding.ASCII.GetString(buf));
                 _recHandler(buf);
             }
         }
     }
     if (_socket != null)
     {
         _socket.BeginReceive(ReceiveAsyn, this);
     }
 }
예제 #24
0
        private void ProcessRecvQueue()
        {
            while (!recvQueue.IsEmpty)
            {
                byte[] data      = null;
                bool   isSuccess = recvQueue.TryDequeue(out data);
                if (!isSuccess || data == null)
                {
                    continue;
                }
                mKcp.Input(data);
                mNeedUpdateFlag = true;

                for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
                {
                    var packet = new byte[size];
                    if (mKcp.Recv(packet) > 0)
                    {
                        RecvDataHandler(packet);
                    }
                }
            }
        }
예제 #25
0
파일: FSPClient.cs 프로젝트: zj831007/SGF
        private void DoReceiveInMain()
        {
            m_RecvBufQueue.Switch();
            while (!m_RecvBufQueue.Empty())
            {
                var recvBufferRaw = m_RecvBufQueue.Pop();
                int ret           = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);

                //收到的不是一个正确的KCP包
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包, Ret:{0}", ret);
                    return;
                }

                m_NeedKcpUpdateFlag = true;

                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (m_Kcp.Recv(recvBuffer) > 0)
                    {
                        m_lastRecvTimestamp = (uint)TimeUtils.GetTotalMillisecondsSince1970();

                        var data = PBSerializer.NDeserialize <FSPDataS2C>(recvBuffer);

                        if (m_RecvListener != null)
                        {
                            for (int i = 0; i < data.frames.Count; i++)
                            {
                                m_RecvListener(data.frames[i]);
                            }
                        }
                    }
                }
            }
        }
예제 #26
0
파일: FSPSession.cs 프로젝트: zj831007/SGF
        private void DoReceiveInMain()
        {
            m_RecvBufQueue.Switch();

            while (!m_RecvBufQueue.Empty())
            {
                var recvBufferRaw = m_RecvBufQueue.Pop();
                int ret           = m_Kcp.Input(recvBufferRaw, recvBufferRaw.Length);

                //收到的不是一个正确的KCP包
                if (ret < 0)
                {
                    Debuger.LogError("收到不正确的KCP包!Ret:{0}", ret);
                    return;
                }

                m_NeedKcpUpdateFlag = true;

                for (int size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
                {
                    var recvBuffer = new byte[size];
                    if (m_Kcp.Recv(recvBuffer) > 0)
                    {
                        if (m_listener != null)
                        {
                            FSPDataC2S data = PBSerializer.NDeserialize <FSPDataC2S>(recvBuffer);
                            m_listener(data);
                        }
                        else
                        {
                            Debuger.LogError("找不到接收者!");
                        }
                    }
                }
            }
        }
예제 #27
0
    void process_recv_queue()
    {
        mRecvQueue.Switch();

        while (!mRecvQueue.Empty())
        {
            var buf = mRecvQueue.Pop();

            mKcp.Input(buf);
            mNeedUpdateFlag = true;

            for (var size = mKcp.PeekSize(); size > 0; size = mKcp.PeekSize())
            {
                var buffer = new byte[size];
                if (mKcp.Recv(buffer) > 0)
                {
                    //evHandler(buffer);
                    //这里开始解包

                    try
                    {
                        //解析并派发
                        ByteArray ba = new ByteArray();
                        ba.WriteALLBytes(buffer);
                        ProtocolRequestBase msg = Analysis(ba);

                        ProtocolAnalysisService.AnalysisAndDispatchMessage(this, msg);
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("AnalysisAndDispatchMessage :\nException: " + e.ToString());
                    }
                }
            }
        }
    }
예제 #28
0
 void process_recv_queue()
 {
     m_RecvQueue.Switch();
     while (!m_RecvQueue.Empty())
     {
         if (m_Kcp == null)
         {//退出
             return;
         }
         var buf = m_RecvQueue.Pop();
         m_Kcp.Input(buf);
         m_NeedUpdateFlag = true;
         int size = m_Kcp.PeekSize();
         //UnityEngine.Main.Debug("size:" + size);
         for (; size > 0; size = m_Kcp.PeekSize())
         {
             var buffer = new byte[size];
             if (m_Kcp.Recv(buffer) > 0)
             {
                 Recv(buffer);
             }
         }
     }
 }
예제 #29
0
        protected override void OnConnectionPacketReceived(ByteBuffer recv_buffer)
        {
            _kcp.Input(recv_buffer.data, recv_buffer.readableBytes);

            var length = _kcp.PeekSize();

            if (length > 0)
            {
                var buffer = ByteBufferPooledAllocator.Default.Alloc(length);

                try
                {
                    var size = _kcp.Recv(buffer.data); //接受数据
                    buffer._SetPosition(size);         // 不想改kcp的实现细节,所以这里简单地强制改buffer长度标记
                    base.OnConnectionPacketReceived(buffer);
                }
                finally
                {
                    buffer.Release();
                }
            }
        }
예제 #30
0
    public override int Receive(byte[] data)
    {
        // 上次剩下的部分
        if (mRecvBuffer.ReadableBytes > 0)
        {
            var recvBytes = Math.Min(mRecvBuffer.ReadableBytes, data.Length);
            Buffer.BlockCopy(mRecvBuffer.RawBuffer, mRecvBuffer.ReaderIndex, data, 0, recvBytes);
            mRecvBuffer.ReaderIndex += recvBytes;
            // 读完重置读写指针
            if (mRecvBuffer.ReaderIndex == mRecvBuffer.WriterIndex)
            {
                mRecvBuffer.Clear();
            }
            return(recvBytes);
        }

        if (mSocket == null)
        {
            return(-1);
        }

        if (!mSocket.Poll(0, SelectMode.SelectRead))
        {
            return(0);
        }

        var rn = 0;

        try
        {
            rn = mSocket.Receive(mRecvBuffer.RawBuffer, mRecvBuffer.WriterIndex, mRecvBuffer.WritableBytes, SocketFlags.None);
            string str = System.Text.Encoding.UTF8.GetString(mRecvBuffer.RawBuffer);
            if (str.StartsWith(ASIO_KCP_SEND_BACK_CONV_PACKET))
            {
                if (in_connect_stage_)
                {
                    connectTimer.Stop();
                    connectTimer.Dispose();
                    in_connect_stage_ = false;
                    string retCodeStr = str.Replace(ASIO_KCP_SEND_BACK_CONV_PACKET, "");
                    uint   retCodeInt = uint.Parse(retCodeStr);
                    CreateKCP(retCodeInt);
                    mRecvBuffer.Clear();
                    Debug.Log("KCP 连接成功" + retCodeInt);
                }
                else
                {
                    Debug.Log("ERROR:KCP 已经连接上了,重复的连接消息");
                }
                mRecvBuffer.Clear();
                return(0);
            }
            else if (str.StartsWith(ASIO_KCP_DISCONNECT_PACKET))
            {
                mRecvBuffer.Clear();
                return(0);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            rn = -1;
        }

        if (rn <= 0)
        {
            return(rn);
        }
        mRecvBuffer.WriterIndex += rn;

        var inputN = mKCP.Input(mRecvBuffer.RawBuffer, mRecvBuffer.ReaderIndex, mRecvBuffer.ReadableBytes, true, true);

        if (inputN < 0)
        {
            mRecvBuffer.Clear();
            return(inputN);
        }
        mRecvBuffer.Clear();

        // 读完所有完整的消息
        for (; ;)
        {
            var size = mKCP.PeekSize();
            if (size <= 0)
            {
                break;
            }

            mRecvBuffer.EnsureWritableBytes(size);

            var n = mKCP.Recv(mRecvBuffer.RawBuffer, mRecvBuffer.WriterIndex, size);
            if (n > 0)
            {
                mRecvBuffer.WriterIndex += n;
            }
        }

        // 有数据待接收
        if (mRecvBuffer.ReadableBytes > 0)
        {
            return(Receive(data));
        }

        return(0);
    }