Exemplo n.º 1
0
        /// <summary>
        /// 解析一个数据包
        /// 不足一个封包时返回null
        /// </summary>
        /// <param name="streamReader">数据读取器</param>
        /// <param name="packet">数据包</param>
        /// <returns></returns>
        public static bool Parse(ISessionStreamReader streamReader, out FastPacket packet)
        {
            packet = null;
            const int packetMinSize = 16;

            if (streamReader.Length < packetMinSize || streamReader[0] != FastPacket.Mark)
            {
                return(false);
            }

            streamReader.Position = 1;
            var totalBytes = streamReader.ReadInt32();

            if (totalBytes < packetMinSize)
            {
                return(false);
            }

            // 数据包未接收完整
            if (streamReader.Length < totalBytes)
            {
                return(true);
            }

            // api名称数据长度
            var apiNameLength = streamReader.ReadByte();

            if (totalBytes < apiNameLength + packetMinSize)
            {
                return(false);
            }

            // api名称数据
            var apiNameBytes = streamReader.ReadArray(apiNameLength);
            // 标识符
            var id = streamReader.ReadInt64();
            // 是否为客户端封包
            var isFromClient = streamReader.ReadBoolean();
            // 是否异常
            var isException = streamReader.ReadBoolean();
            // 实体数据
            var body = streamReader.ReadArray(totalBytes - streamReader.Position);

            // 清空本条数据
            streamReader.Clear(totalBytes);

            var apiName = Encoding.UTF8.GetString(apiNameBytes);

            packet = new FastPacket(apiName, id, isFromClient)
            {
                TotalBytes    = totalBytes,
                ApiNameLength = apiNameLength,
                IsException   = isException,
                Body          = body
            };
            return(true);
        }