Esempio n. 1
0
        public void UnPacket(PacketHead head, byte[] byteArray, int offset, int length)
        {
            Proto.MsgId msgId = (Proto.MsgId)head.msg_id;
            if (!_msgHandler.ContainsKey(msgId))
            {
                UnityEngine.Debug.LogWarning("!!!!! not found handler. recv packet msgId:" + head.msg_id);
                return;
            }

            Google.Protobuf.IMessage msg = _msgHandler[msgId](byteArray, offset, length);
            MessagePackDispatcher.GetInstance().Broadcasting(head.msg_id, msg);
        }
Esempio n. 2
0
        public void Update()
        {
            if (_sock == null)
            {
                return;
            }

            if (_state != NetworkState.Connected)
            {
                return;
            }

            try
            {
                // 接收数据
                while (true)
                {
                    var bufAvail = this._recvBuf.Length - this._recvIndex;
                    if (bufAvail <= 0)
                    {
                        break;
                    }

                    if (_sock.Available <= 0)
                    {
                        break;
                    }

                    int receivedSize = _sock.Receive(_recvBuf, _recvIndex, bufAvail, SocketFlags.None);
                    _recvIndex += receivedSize;
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogError(ex.Message);
                Disconnect();
                return;
            }

            // 如果收到的数据没有达到包头的数据大小,继续等待读包
            if (_recvIndex < PacketHead.HeadSize)
            {
                return;
            }

            // 拆包
            while (_recvIndex >= PacketHead.HeadSize)
            {
                PacketHead   head       = new PacketHead();
                var          byteStream = new MemoryStream(_recvBuf);
                BinaryReader br         = new BinaryReader(byteStream);
                var          totalLen   = br.ReadUInt16();
                var          headLen    = br.ReadUInt16();
                head.msg_id = br.ReadUInt16();

                // 如果收到的数据包不完整
                if (totalLen > _recvIndex)
                {
                    break;
                }

                UnPacket(head, _recvBuf, (int)byteStream.Position, totalLen - PacketHead.HeadSize);

                // 有协议可能会关闭网络
                if (_state != NetworkState.Connected)
                {
                    return;
                }

                _recvIndex -= totalLen;

                UnityEngine.Debug.LogFormat($"_recv_index:{_recvIndex}, msgid:{(Proto.MsgId)head.msg_id}, msg total len:{totalLen}");

                // 剩余字节放在缓冲区前面去
                if (_recvIndex > 0)
                {
                    Array.Copy(_recvBuf, totalLen, _recvBuf, 0, _recvIndex);
                }
            }
        }