Common.cs 3.1 KB
using System;
using System.IO;
using System.Linq;
using System.Text;

namespace AGVLib
{
    public class Common
    {
        //包开始字节
        public static byte[] headPack = new byte[] { 0xAB, 0xBA };
        public static int headSize = 6;//包头识别符2+包头长度4
        public static bool CheckHeadChar(byte[] bytes, out int starIdx)
        {
            starIdx = -1;
            for (int i = 0; i < bytes.Length - headPack.Length + 1; i++)
            {
                int j = 0;
                for (j = 0; j < headPack.Length; j++)
                {
                    if (!bytes[i + j].Equals(headPack[j]))
                        break;
                }
                if (j == headPack.Length)
                {
                    starIdx = i;
                    return true;
                }

            }
            return false;
        }

        //将数字转换成字节数组
        //由数字创建字节数组
        public static byte[] IntToByteArray(int src)
        {
            //创建内存流MemoryStream,stream作为存放 二进制数据 的缓存
            using (MemoryStream stream = new MemoryStream())
            {
                //创建一个BinaryWriter来写二进制数据到stream
                using (BinaryWriter write = new BinaryWriter(stream))
                {
                    write.Write(src);//将十进制数字src写到stream中,
                    return stream.ToArray();//将写到stream中的二进制数据转为字节数组

                }
            }
        }
        /// <summary>
        /// 对节点进行编码
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static byte[] Encode(Node node)
        {
            try
            {
                string json = JsonHelper.SerializeObject(node);
                byte[] body = Encoding.UTF8.GetBytes(json);
                byte[] bodySize = Common.IntToByteArray(body.Length);
                byte[] buff = Common.headPack.Concat(bodySize).Concat(body).ToArray();
                return buff;
            }
            catch
            {
                return new byte[0];
            }
        }
        /// <summary>
        /// 对字节码解码
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        public static Node Decode(byte[] buff)
        {
            try
            {
                byte[] headByte = new byte[headSize];
                Buffer.BlockCopy(buff, 0, headByte, 0, Common.headSize);//从缓冲区里读取包头的字节
                int bodySize = BitConverter.ToUInt16(headByte, 2);//从包头里面分析出包体的长度
                byte[] resBytes = new byte[bodySize];
                Buffer.BlockCopy(buff,headSize, resBytes, 0, bodySize);
                string json = System.Text.Encoding.UTF8.GetString(resBytes);
                Node node = JsonHelper.DeserializeJsonToObject<Node>(json);
                return node;
            }
            catch
            {
                return null;
            }
        }
    }
}