Ejemplo n.º 1
0
 /// <summary>
 /// 转换字节序
 /// </summary>
 /// <param name="header"></param>
 /// <returns></returns>
 public static PBHead ConvertByteOrder(PBHead header)
 {
     header.mBodyLen   = IPAddress.HostToNetworkOrder(header.mBodyLen);
     header.mMessageId = IPAddress.HostToNetworkOrder(header.mMessageId);
     header.mTimeStamp = IPAddress.HostToNetworkOrder(header.mTimeStamp);
     return(header);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 生成消息包
        /// </summary>
        /// <param name="pbbody"></param>
        /// <returns></returns>
        public static PBPacket NewPacket(PBBody pbbody)
        {
            PBPacket packet = new PBPacket();
            PBHead   header = new PBHead();

            header.mMessageId = GetPacketId(pbbody.GetType());
            header.mBodyLen   = GetPBBodyLength(pbbody);
            header.mTimeStamp = DateTime.Now.Ticks;

            packet.mHead = header;
            packet.mBody = pbbody;

            return(packet);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 将流转包头
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static PBHead Buffer2Head(byte[] bytes)
        {
            int    size   = PBConst.PB_HEAD_SIZE;
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try {
                Marshal.Copy(bytes, 0, buffer, size);
                PBHead header = (PBHead)Marshal.PtrToStructure(buffer, typeof(PBHead));
                // 接收到的byte需要转换字节序
                header.mBodyLen   = header.mBodyLen;
                header.mMessageId = header.mMessageId;
                header.mTimeStamp = header.mTimeStamp;
                return(header);
            } finally {
                Marshal.FreeHGlobal(buffer);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 将头转为流
        /// </summary>
        /// <param name="header"></param>
        /// <param name="isByteOrder"></param>
        /// <returns></returns>
        public static byte[] Head2Buffer(PBHead header, bool isByteOrder = true)
        {
            if (isByteOrder)
            {
                header = ConvertByteOrder(header);
            }
            int    size   = PBConst.PB_HEAD_SIZE;
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try {
                Marshal.StructureToPtr(header, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return(bytes);
            } finally {
                Marshal.FreeHGlobal(buffer);
            }
        }