Unity编码工具类

20 篇文章 2 订阅
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace AhpilyServer
{
    /// <summary>
    /// 编码工具类
    /// </summary>
    public class EncodeTool
    {

        #region 粘包 拆包

        /// <summary>
        /// 构造包:包头+包体
        /// </summary>
        public static byte[] EncodePacket(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(data.Length);
                    bw.Write(data);

                    byte[] bytes = new byte[ms.Length];
                    Buffer.BlockCopy(ms.GetBuffer(), 0, bytes,0, (int)ms.Length);
                    return bytes;
                }
            }
        }

        /// <summary>
        /// 包解析
        /// </summary>
        public static byte[] DecodePacket(ref List<byte> dataCache)
        {
            if (dataCache.Count < 4)
            {
                //Console.WriteLine("数据长度不足4");
                return null;
            }

            using (MemoryStream ms = new MemoryStream(dataCache.ToArray()))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    int lenth = br.ReadInt32();
                    int dataRemainLenth = (int) (ms.Length - ms.Position);

                    if (lenth > dataRemainLenth)
                    {
                        Console.WriteLine("数据长度不足约定长度,数据没有传完");
                        return null;
                    }

                    byte[] datas = br.ReadBytes(lenth);
                    dataCache.Clear();
                    dataCache.AddRange(br.ReadBytes(dataRemainLenth));
                    return datas;
                }
            }
        }

        #endregion

        #region 构造SocketMessage类

        /// <summary>
        /// 将一个Message类转为数组
        /// </summary>
        /// <returns></returns>
        public static byte[] EncodeMessage(SocketMessage message)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(message.OpCode);
                    bw.Write(message.SubCode);

                    if (message.Value != null)
                    {
                        byte[] values = EncodeObject(message.Value);
                        bw.Write(values);
                    }

                    byte[] bytes = new byte[ms.Length];
                    Buffer.BlockCopy(ms.GetBuffer(), 0, bytes, 0, (int)ms.Length);
                    return bytes;
                }
            }
        }

        /// <summary>
        /// 将收到的字节转为对象
        /// </summary>
        public static SocketMessage DecodeMessage(byte[] datas)
        {
            using (MemoryStream ms = new MemoryStream(datas))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    SocketMessage socketMessage = new SocketMessage();
                    socketMessage.OpCode = br.ReadInt32();
                    socketMessage.SubCode = br.ReadInt32();

                    if (ms.Length > ms.Position)
                    {
                        byte[] valueBytes = br.ReadBytes((int) (ms.Length - ms.Position));
                        socketMessage.Value = DecodeObject(valueBytes);
                    }

                    return socketMessage;
                }
            }
        }

        #endregion

        #region 将object转为byte[]

        /// <summary>
        /// 序列化对象
        /// </summary>
        public static byte[] EncodeObject(object message)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(ms, message);

                byte[] bytes = new byte[ms.Length];
                Buffer.BlockCopy(ms.GetBuffer(), 0, bytes, 0, (int)ms.Length);
                return bytes;
            }
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public static object DecodeObject(byte[] datas)
        {
            using (MemoryStream ms = new MemoryStream(datas))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                return binaryFormatter.Deserialize(ms);
            }
        }

        #endregion

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值