新文章 网摘 文章 随笔 日记

自己写的TCP自定义二进制协议(三)

namespace BinaryProtocol.Core.Models
{
    public interface IMessage<T>
    {
        /// <summary>
        /// 消息头
        /// </summary>
        MessageHead Head { get; }
        /// <summary>
        /// 消息体
        /// </summary>
        IMessageBody<T> Body { get; }
        /// <summary>
        /// 将整个消息转换为字节
        /// </summary>
        /// <returns></returns>
        byte[] Bytes { get; }
    }
}
namespace BinaryProtocol.Core.Models
{
    public interface IMessageBody<T>
    {
        /// <summary>
        /// 转换为字节
        /// </summary>
        /// <returns></returns>
        byte[] Bytes { get; }
        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <returns></returns>
        T Value { get; }
    }
}
namespace BinaryProtocol.Core.Models
{
    /// <summary>
    /// 要编码的消息实体的接口
    /// </summary>
    public interface IMessageEntity
    {
    }
}
using System;

namespace BinaryProtocol.Core.Models
{
    /// <summary>
    /// 消息
    /// </summary>
    public class Message<T>: IMessage<T>
    {
        private byte[] _bytes;
        public MessageHead Head { get; }
        public IMessageBody<T> Body { get; }
        public Message(MessageHead head, IMessageBody<T> body)
        {
            Head = head;
            Body = body;
        }

        public byte[] Bytes
        {
            get
            {
                if (_bytes != null)
                {
                    return _bytes;
                }
                byte[] headBuff = Head.Bytes;
                byte[] bodyBuff = Body.Bytes;
                var len = headBuff.Length + bodyBuff.Length;
                _bytes = new byte[len];

                Buffer.BlockCopy(headBuff, 0, _bytes, 0, headBuff.Length);
                Buffer.BlockCopy(bodyBuff, 0, _bytes, headBuff.Length, bodyBuff.Length);
                return _bytes;
            }
        }
    }
}
using BinaryProtocol.Core.Coder;

namespace BinaryProtocol.Core.Models
{
    public class MessageBody<T> : IMessageBody<T>
    {
        /// <summary>
        /// 消息体内容
        /// </summary>
        private T _content;
        private byte[] _bytes;
        public MessageBody(T content)
        {
            _content = content;
        }

        public MessageBody(byte[] bytes)
        {
            _bytes = bytes;
        }
        /// <summary>
        /// 将消息体转换为字节
        /// </summary>
        /// <returns></returns>
        public virtual byte[] Bytes
        {
            get
            {
                if (_bytes != null)
                {
                    return _bytes;
                }
                var bitEncoder = new BitEncoder<T>(_content);
                _bytes = bitEncoder.Bytes;

                return _bytes;
            }
        }
        /// <summary>
        /// 将字节反序列化为对象
        /// </summary>
        /// <returns></returns>
        public virtual T Value
        {
            get
            {
                if (_content != null)
                {
                    return _content;
                }

                var bitDecoder = new BitDecoder<T>(_bytes);
                _content = bitDecoder.Value;

                return _content;
            }

        }
    }
}
using System;

namespace BinaryProtocol.Core.Models
{
    /// <summary>
    /// 消息头
    /// </summary>
    public class MessageHead
    {
        private byte[] _bytes;
        /// <summary>
        /// 消息头长度
        /// </summary>
        public const int HeadLength = 11;
        /// <summary>
        /// 消息Id
        /// </summary>
        public int Id { get; }
        /// <summary>
        /// 协议类型
        /// </summary>
        public byte ProtocolType { get; }
        /// <summary>
        /// 消息类型
        /// </summary>
        public byte MessageType { get; }
        /// <summary>
        /// 消息版本
        /// </summary>
        public byte Version { get; }


        public int BodyLength { get; }

        public MessageHead(int id, byte protocolType, byte messageType, byte version, int bodyLength)
        {
            Id = id;
            ProtocolType = protocolType;
            MessageType = messageType;
            Version = version;
            BodyLength = bodyLength;
        }

        public MessageHead(byte[] bytes)
        {
            _bytes = bytes;
            BodyLength = BitConverter.ToInt32(bytes, 0);
            Version = bytes[4];
            MessageType = bytes[5];
            ProtocolType = bytes[6];
            Id = BitConverter.ToInt32(bytes, 7);
        }
        public byte[] Bytes
        {
            get
            {
                if (_bytes != null)
                {
                    return _bytes;
                }
                _bytes = new byte[HeadLength];
                byte[] bodyLenBuff = BitConverter.GetBytes(BodyLength);
                byte[] versionBuff = BitConverter.GetBytes(Version);
                byte[] msgTypeBuff = BitConverter.GetBytes((byte)MessageType);
                byte[] protocolTypeBuff = BitConverter.GetBytes((byte)ProtocolType);
                byte[] idBuff = BitConverter.GetBytes(Id);

                Buffer.BlockCopy(bodyLenBuff, 0, _bytes, 0, bodyLenBuff.Length);
                Buffer.BlockCopy(versionBuff, 0, _bytes, 4, versionBuff.Length);
                Buffer.BlockCopy(msgTypeBuff, 0, _bytes, 5, msgTypeBuff.Length);
                Buffer.BlockCopy(protocolTypeBuff, 0, _bytes, 6, msgTypeBuff.Length);
                Buffer.BlockCopy(idBuff, 0, _bytes, 7, idBuff.Length);
                return _bytes;
            }
        }

    }
}
using System;

namespace BinaryProtocol.Core.Attributes
{
    /// <summary>
    /// 指定字段在编码中的顺序
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class FieldIndex : Attribute
    {
        public int Index { get; }
        public FieldIndex(int index)
        {
            Index = index;
        }
    }
}
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BinaryProtocol.Core.Text
{
    public class JsonHelper
    {
        private readonly string _fileFullName;
        public JsonHelper(string fileFullName)
        {
            _fileFullName = fileFullName;
        }
        /// <summary>
        /// 加载整个文件并反序列化为一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Get<T>()
        {
            if (!File.Exists(_fileFullName))
            {
                return default(T);
            }
            string jsonStr = File.ReadAllText(_fileFullName);
            var result = JsonConvert.DeserializeObject<T>(jsonStr);
            return result;
        }
        /// <summary>
        /// 从Json文件中读取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyLink">对象的键名链,例如 Order.User</param>
        /// <returns>类型为T的对象</returns>
        public T Get<T>(string keyLink)
        {
            if (!File.Exists(_fileFullName))
            {
                return default(T);
            }

            using (StreamReader streamReader = new StreamReader(_fileFullName))
            {
                string jsonStr = streamReader.ReadToEnd();
                dynamic obj = JsonConvert.DeserializeObject(jsonStr);
                var keys = keyLink.Split('.');
                dynamic currentObject = obj;
                foreach (var key in keys)
                {
                    currentObject = currentObject[key];
                    if (currentObject == null)
                    {
                        return default(T);
                    }
                }

                var result = JsonConvert.DeserializeObject<T>(currentObject.ToString());
                return result;
            }

        }
        /// <summary>
        /// 设置对象值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyLink">对象的键名链,例如 Order.User,当其上级不存在时将创建</param>
        /// <param name="value"></param>
        public void Set<T>(string keyLink, T value)
        {
            string jsonStr = File.ReadAllText(_fileFullName);
            dynamic obj = JsonConvert.DeserializeObject(jsonStr);
            var keys = keyLink.Split('.');
            dynamic currentObject = obj;

            for (int i = 0; i < keys.Length; i++)
            {
                var oldObject = currentObject;
                currentObject = currentObject[keys[i]];
                var isValueType = value.GetType().IsValueType;

                if (i == keys.Length - 1)
                {
                    if (isValueType || value is string)
                    {
                        oldObject[keys[i]] = new JValue(value);
                    }
                    else
                    {
                        oldObject[keys[i]] = (JObject)JToken.FromObject(value);
                    }

                }
                else
                {
                    //如果不存在,新建
                    if (currentObject == null)
                    {
                        JObject o = (JObject)JToken.FromObject(new object());
                        oldObject[keys[i]] = o;
                        currentObject = oldObject[keys[i]];
                    }
                }
            }
            Save<dynamic>(obj);
        }
        /// <summary>
        /// 保存Json文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public void Save<T>(T obj)
        {
            string str = JsonConvert.SerializeObject(obj, Formatting.Indented);
            File.WriteAllText(_fileFullName, str);
        }
    }
}

 

posted @ 2020-10-27 17:01  岭南春  阅读(116)  评论(0)    收藏  举报