Exemple #1
0
        void HandleConnectAck(UInt32 now)
        {
            if (recvQueue_.Empty())
            {
                recvQueue_.Switch();
            }

            while (status_ == Status.Connecting && !recvQueue_.Empty())
            {
                var buf = recvQueue_.Pop();
                if (kcpCommand_.Decode(buf, buf.Length) < 0)
                {
                    return;
                }

                if (kcpCommand_.cmd == KcpCmd.KCP_CMD_CONNECT_ACK)
                {
                    InitKcp(kcpCommand_.conv);
                    lastRecvTime_ = now;
                    status_       = Status.Connected;
                    eventCallback_(conv_, KcpEvent.KCP_EV_CONNECT, null, null);
                    break;
                }
            }
        }
Exemple #2
0
    void process_connect_packet()
    {
        mRecvQueue.Switch();

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

            UInt32 conv = 0;
            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_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);
                }
            }
        }
    }
Exemple #4
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);

                        m_listener.OnReceive(this, msg);
                    }
                }
            }
        }
Exemple #5
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);
                    }
                }
            }
        }
Exemple #6
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);
                    }
                }
            }
        }
        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("找不到接收者!");
                        }
                    }
                }
            }
        }
Exemple #8
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);
                    }
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// 更新
        /// </summary>
        public void Update()
        {
            foreach (var c in channels.Values)
            {
                c.Update();
            }

            foreach (var conv in removePool)
            {
                if (channels.ContainsKey(conv))
                {
                    channels.Remove(conv);
                    Debug.Log("断开一个链接,剩余链接" + channels.Count);
                }
            }
            removePool.Clear();

            recvQueue.Switch();
            while (!recvQueue.Empty())
            {
                if (OnReciveCallBack == null)
                {
                    recvQueue.Clear();
                }
                else
                {
                    OnReciveCallBack?.Invoke(0, recvQueue.Pop());
                }
            }
        }
Exemple #10
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);
        }
Exemple #11
0
 public void ProcessInput()
 {
     INPUT_QUEUE.Switch();
     while (!INPUT_QUEUE.isEmpty)
     {
         string cmd = INPUT_QUEUE.Pop();
         this.cmdHandler(cmd);
     }
 }
Exemple #12
0
 public static void Sync()
 {
     PENDING_LIST.Switch();
     while (!PENDING_LIST.isEmpty)
     {
         BaseEvent e = PENDING_LIST.Pop();
         Invoke(e);
     }
 }
Exemple #13
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);
                    }
                }
            }
        }
    }
Exemple #14
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);
                        }
                    }
                }
            }
        }
Exemple #15
0
        private static void UpdateLogic(float rdt, float fdt)
        {
            _elapsed += rdt;

            //如果本地frame比服务端慢,则需要快速步进追赶服务端帧数
            SERVER_KEYFRAMES.Switch();
            while (!SERVER_KEYFRAMES.isEmpty)
            {
                _DTO_frame_info dto    = SERVER_KEYFRAMES.Pop();
                int             length = dto.frameId - lBattle.frame;
                while (length >= 0)
                {
                    if (length == 0)
                    {
                        HandleAction(dto);
                    }
                    else
                    {
                        lBattle.Simulate(_elapsed, fdt);
                        _elapsed = 0f;
                    }
                    --length;
                }
                _nextKeyFrame = dto.frameId + _framesPerKeyFrame;
            }

            if (lBattle.frame < _nextKeyFrame)
            {
                _elapsedSinceLastLogicUpdate += rdt;

                while (_elapsedSinceLastLogicUpdate >= fdt)
                {
                    if (lBattle.frame >= _nextKeyFrame)
                    {
                        break;
                    }

                    lBattle.Simulate(_elapsed, fdt);

                    if (lBattle.frame == _nextKeyFrame)
                    {
                        _sendActionFrame   = lBattle.frame;
                        _shouldSendActions = true;
                    }

                    _elapsed = 0f;
                    _elapsedSinceLastLogicUpdate -= fdt;
                }
            }
        }
        private void OnRecevie()
        {
            _recvQueue.Switch();
            while (!_recvQueue.Empty())
            {
                byte[] bytes = _recvQueue.Pop();
                _protocolHead.Reset();
                _protocolHead.Deserialize(bytes);
                _recvStream.Seek(0, SeekOrigin.Begin);
                _recvStream.SetLength(0);
                _recvStream.Write(bytes, ProtocolHead.Size, (int)_protocolHead.len + 4 - ProtocolHead.Size);
                _recvStream.Seek(0, SeekOrigin.Begin);
                Protocol.Protocol protocol = Protocol.Protocol.GetProtocolThreadSafe(_protocolHead.msgId);
                if (protocol == null)
                {
#if DEBUG
                    Debug.LogError("Ptc Not found: " + _protocolHead.msgId.ToString());
#endif
                    continue;
                }
                try {
#if DEBUG
                    if (_protocolHead.len > 1024)
                    {
                        Debug.LogWarning("Recv Ptc:" + protocol.GetMessageID().ToString() + " to long:" + _protocolHead.len.ToString());
                    }
#endif

                    protocol.ThreadErrorCode = ProtocolErrorCode.NO_ERROR;
                    protocol.DeSerialize(_recvStream);
                    Protocol.Protocol.ReturnProtocolThreadSafe(protocol);
                } catch (Exception ex) {
                    Debug.LogWarning("Ptc " + _protocolHead.msgId.ToString() + " deserialize fail: " + ex.Message.ToString());
                    protocol.ThreadErrorCode = ProtocolErrorCode.DESERIALIZE_ERROR;
                }
                if (protocol.ThreadErrorCode == ProtocolErrorCode.NO_ERROR)
                {
                    try {
                        protocol.Process();
                    } catch (Exception ex) {
                        Debug.LogWarning("Ptc " + _protocolHead.msgId.ToString() + " Process fail: " + ex.Message.ToString());
                        protocol.ThreadErrorCode = ProtocolErrorCode.PROCESS_ERROR;
                    } finally {
                        Protocol.Protocol.ReturnProtocolThreadSafe(protocol);
                    }
                }
            }
        }
Exemple #17
0
        public void Update(long dt)
        {
            //如果本地frame比服务端慢,则需要快速步进追赶服务端帧数
            SERVER_KEYFRAMES.Switch();
            while (!SERVER_KEYFRAMES.isEmpty)
            {
                _DTO_frame_info dto    = SERVER_KEYFRAMES.Pop();
                int             length = dto.frameId - this.frame;
                while (length >= 0)
                {
                    if (length == 0)
                    {
                        this.HandleAction(dto);
                    }
                    else
                    {
                        this.Simulate(this._msPerFrame);
                    }
                    --length;
                }

                this._nextKeyFrame = dto.frameId + this._framesPerKeyFrame;
            }

            if (this.frame < this._nextKeyFrame)
            {
                this._lastElapsed += dt;

                while (this._lastElapsed >= this._msPerFrame)
                {
                    if (this.frame >= this._nextKeyFrame)
                    {
                        break;
                    }

                    this.Simulate(this._msPerFrame);

                    if (this.frame == this._nextKeyFrame)
                    {
                        this.transmitter.SendAll(LVProtoMgr._PACKET_BATTLE_KEYFRAME(this.frame));
                    }

                    this._lastElapsed -= this._msPerFrame;
                }
            }
        }
Exemple #18
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);
                    }
                }
            }
        }
Exemple #19
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);
                }
            }
        }
    }
Exemple #20
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);
        }
Exemple #21
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);
        }
Exemple #22
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)
                    {
                        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]);
                            }
                        }
                    }
                }
            }
        }
Exemple #23
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)
                    {
                        if (m_listener != null)
                        {
                            FSPDataC2S data = PBSerializer.NDeserialize <FSPDataC2S>(recvBuffer);
                            m_listener(data);
                        }
                        else
                        {
                            Debuger.LogError("找不到接收者!");
                        }
                    }
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// 仅仅在UpdateRepeatedly里面调用。
        /// 如果是握手信息,则创建Session,并返回握手应答;否则让ClientSession自己处理。
        /// </summary>
        private void ProcessRecvQueue()
        {
            mRecvQueue.Switch();
            while (!mRecvQueue.Empty())
            {
                var e = mRecvQueue.Pop();
                if (e.BytesTransferred == 0)
                { //说明客户端关闭了,GG:UDP不知道客户端关闭的事情吧?
                    PushSAE(e);
                    continue;
                }

                uint index;
                if (TryProcessHandShake(e, out index))
                {
                    continue;
                }

                try
                {
                    KCPLib.ikcp_decode32u(e.Buffer, e.Offset, ref index);
                    var clientSession = GetSession(index);
                    if (clientSession != null && clientSession.Status == ClientSessionStatus.Connected)
                    {
                        Debug.Assert(clientSession.EndPoint.ToString() == e.RemoteEndPoint.ToString());
                        //c.EndPoint = e.RemoteEndPoint;

                        clientSession.process_recv_queue(e);
                    }
                }
                finally
                {  //GG: 使用Disposeale将PushSAE放在一起。简化代码。
                    PushSAE(e);
                }
            }
        }
Exemple #25
0
 private static void ProcessInput()
 {
     INPUT_QUEUE.Switch();
     while (!INPUT_QUEUE.isEmpty)
     {
         string cmd = INPUT_QUEUE.Pop();
         if (cmd == "exit")
         {
             Dispose();
         }
         else if (cmd == "cls")
         {
             Console.Clear();
         }
         else if (cmd == "stop")
         {
             NetworkManager.StopServer(NETWORK_NAME);
         }
         else if (cmd == "start")
         {
             NetworkManager.StartServer(NETWORK_NAME, _port);
         }
     }
 }
Exemple #26
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());
                    }
                }
            }
        }
    }
Exemple #27
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);
             }
         }
     }
 }
Exemple #28
0
        private void ProcessRecvQueue()
        {
            mRecvQueue.Switch();
            while (!mRecvQueue.Empty())
            {
                var e = mRecvQueue.Pop();
                if (e.BytesTransferred == 0)
                {
                    PushSAE(e);
                    //说明客户端关闭了
                    continue;
                }
                uint index = 0, key = 0;
                //使用纯udp进行握手,8字节0xFF+4字节conv+4字节key
                if (IsHandshake(e.Buffer, e.Offset, e.BytesTransferred, out index, out key))
                {
                    var  c  = GetSession(index);
                    uint cc = 0;
                    KCPLib.ikcp_decode32u(e.Buffer, e.Offset + 16, ref cc);
                    if (c == null)
                    {
                        bool add = true;
                        //新连接处理,如果返回false,则不予处理,可以用来进行非法连接的初步处理
                        if (NewSessionProcessor != null)
                        {
                            add = NewSessionProcessor.OnNewSession(index, e.RemoteEndPoint);
                        }
                        if (add == false)
                        {
                            PushSAE(e);
                            continue;
                        }
                        c                     = AddSession(e.RemoteEndPoint, index);
                        c.m_KCPServer         = this;
                        c.m_LastRecvTimestamp = m_watch.Elapsed;
                        OnNewClientSession(c, e.Buffer, e.Offset, e.BytesTransferred);
#if DEV
                        IRQLog.AppLog.Log(index.ToString() + ",连接1," + cc.ToString());
#endif
                    }
                    else
                    {
#if DEV
                        IRQLog.AppLog.Log(index.ToString() + ",连接2," + cc.ToString());
#endif
                        c.EndPoint = e.RemoteEndPoint;
                        //如果客户端关闭并且立刻重连,这时候是连不上的,因为KCP中原有的数据不能正确处理
                        //c.ResetKCP();
                    }

                    c.Status = ClientSessionStatus.Connected;
                    //回发握手请求
                    if (UdpLibConfig.ServerSendAsync)
                    {
                        m_UdpSocket.SendToAsync(e);
                    }
                    else
                    {
#if DEBUG
                        Stopwatch sw = Stopwatch.StartNew();
                        m_UdpSocket.SendTo(e.Buffer, e.Offset, e.BytesTransferred, SocketFlags.None, e.RemoteEndPoint);
                        Console.WriteLine((sw.ElapsedTicks * 1000f / Stopwatch.Frequency));
#else
                        m_UdpSocket.SendTo(e.Buffer, e.Offset, e.BytesTransferred, SocketFlags.None, e.RemoteEndPoint);
#endif
                        PushSAE(e);
                    }
#if DEV
                    IRQLog.AppLog.Log(index.ToString() + ",发送数据UDP");
#endif
                }
                else
                {
                    try {
                        KCPLib.ikcp_decode32u(e.Buffer, e.Offset, ref index);
                        var c = GetSession(index);
                        if (c != null && c.Status == ClientSessionStatus.Connected)
                        {
                            Debug.Assert(c.EndPoint.ToString() == e.RemoteEndPoint.ToString());
                            //c.EndPoint = e.RemoteEndPoint;

                            c.process_recv_queue(e);
                        }
                    }
                    finally {
                        PushSAE(e);
                    }
                }
            }
        }