当前位置: 首页 > news >正文

C# 实现TCP/IP通信协议——Message结构设计

(1)通信Message包括报头+消息体+结束符;

(2)报头包含报文Title、发送时间、报文类型,SequenceNo等数据。

(3)内容采用明文,使用空格补足空缺位置。 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace LearnAuto
{public enum MessageType{Heartbeat = '0',       // 心跳报文Application = 'A',     // 应用报文Response = 'C'         // 应答报文}    public class MessageHeader{public byte[] MessageID { get; set; } = new byte[5]; public DateTime DateTime { get; set; }public int Length { get; set; }      // 报文长度 = 报文头长度+报文体长度+结束符长度public MessageType Type { get; set; } // 类型public int SequenceNo { get; set; } // 报文序号public byte[] Reserved { get; set; } = new byte[10]; // 备用public static readonly int HEADER_LENGTH = 43;public static readonly int DATETIME_BYTE_WIDTH = 14;public static readonly int LENGTH_BYTE_WIDTH = 4;public static readonly int SEQUENCE_NO_BYTE_WIDTH = 8;public readonly static string MESSAGE_ID = "HELLO"; // 报文IDpublic void UpdateDateTime(){DateTime = DateTime.Now;}public int BodyLength(){return Length - HEADER_LENGTH - 1;}public static DateTime BytesToDateTime(byte[] bytes){if (bytes == null || bytes.Length != 14)throw new ArgumentException("Byte array must be exactly 8 bytes long.");// 1. 将 byte[8] 转为字符串(假设是 ASCII 编码)string dateTimeStr = Encoding.ASCII.GetString(bytes);// 2. 使用 DateTime.ParseExact 解析格式 "yyyyMMddHHmmss"return DateTime.ParseExact(dateTimeStr, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);}public static int BytesToInt(byte[] bytes){// 2. 转为字符串(假设是 ASCII 编码)string str = Encoding.ASCII.GetString(bytes);// 3. 去除左侧空格str = str.TrimStart();// 4. 转为 int(如果字符串为空或无效,会抛出异常)return int.Parse(str);}public static MessageHeader FromBytes(byte[] data){// 实现从字节数组解析报文using (var ms = new MemoryStream(data))using (var reader = new BinaryReader(ms)){varHeader = new MessageHeader{MessageID = reader.ReadBytes(5),DateTime = BytesToDateTime(reader.ReadBytes(DATETIME_BYTE_WIDTH)),Length = BytesToInt(reader.ReadBytes(LENGTH_BYTE_WIDTH)),Type = (MessageType)reader.ReadByte(),SequenceNo = BytesToInt(reader.ReadBytes(SEQUENCE_NO_BYTE_WIDTH))};return Header;}}// 实现ToBytes方法public byte[] ToBytes(){// 实现报文头序列化为字节数组using (var ms = new MemoryStream())using (var writer = new BinaryWriter(ms)){writer.Write(MessageID);writer.Write(Encoding.ASCII.GetBytes(DateTime.ToString("yyyyMMddHHmmss")));writer.Write(Encoding.ASCII.GetBytes(Length.ToString().PadLeft(4, ' ')));writer.Write((byte)Type);writer.Write(Encoding.ASCII.GetBytes(SequenceNo.ToString().PadLeft(8, ' ')));writer.Write(Reserved);return ms.ToArray();}}}public class MessageBody{public static readonly int SN_LENGTH = 9;public static readonly int MAX_FEATURE_COUNT = 45;public static readonly int FEATURE_BYTE_WIDTH = 8;public static readonly int RESERVED_LENGTH = 16;public static readonly int MSG_BODY_LENGTH = SN_LENGTH + 1 + MAX_FEATURE_COUNT * (FEATURE_BYTE_WIDTH + 1) + RESERVED_LENGTH;public byte[] SN { get; set; } = new byte[SN_LENGTH]; public List<byte[]> FeatureValues = new List<byte[]>(MAX_FEATURE_COUNT); // 特征尺寸,每个尺寸8个字节public byte[] FeatureOK { get; set; } = new byte[MAX_FEATURE_COUNT]; public byte[] Reserved { get; set; } = new byte[RESERVED_LENGTH]; // 备用private static Dictionary<string, int> _dicFeatures = new Dictionary<string, int>
{{"x", 0 },{"xx", 1 },{"xxx", 2 },{"xxxx", 3 },{"xxxxx", 4 }
};public MessageBody(int SN, ref List<(string, double, bool)> result)
{SN = Encoding.ASCII.GetBytes(SN.ToString().PadLeft(SN_LENGTH, ' '));for (int i = 0; i < MAX_FEATURE_COUNT; i++){FeatureValues.Add(new byte[FEATURE_BYTE_WIDTH]);for (int j = 0; j < FEATURE_BYTE_WIDTH; j++){FeatureValues[i][j] = 32; // 空格的ASCII码}FeatureOK[i] = (byte)'0'; // 初始化为0}for (int i = 0; i < RESERVED_LENGTH; i++){Reserved[i] = 32; // 空格的ASCII码}for (int i = 0; i < result.Count; i++){if (SetFeatureValue(result[i].Item1, result[i].Item2, result[i].Item3)){if (result[i].Item3 == false) {IsOK = (byte)'2'; break;}}}}private bool SetFeatureValue( string item, double value, bool isOk){int index = 0;if (_dicFeatures.TryGetValue(item, out int featureIndex)){index = featureIndex;FeatureValues[index] = Encoding.ASCII.GetBytes(value.ToString("F3").PadLeft(8, ' '));FeatureOK[index] = (byte)(isOk ? '1' : '2'); return true;}else{Log.Error("Invalid feature name: " + item);return false;}            }// 实现ToBytes方法public byte[] ToBytes(){// 实现报文头序列化为字节数组using (var ms = new MemoryStream())using (var writer = new BinaryWriter(ms)){writer.Write(SN);foreach (byte[] feature in FeatureValues){writer.Write(feature);}writer.Write(FeatureOK);writer.Write(Reserved);return ms.ToArray();}}}// 报文类public class NetworkMessage{public MessageHeader Header { get; set; }public byte[] Body { get; set; }public static readonly int EXT_LENGTH = 1;public static readonly byte EXT_CHAR = 0x03;public static readonly int MIN_LENGTH = MessageHeader.HEADER_LENGTH + EXT_LENGTH;public void UpdateDateTime(){Header.UpdateDateTime();}public byte[] ToBytes(){// 实现报文序列化为字节数组using (var ms = new MemoryStream())using (var writer = new BinaryWriter(ms)){writer.Write(Header.ToBytes());writer.Write(Body);writer.Write(NetworkMessage.EXT_CHAR); // 结束符return ms.ToArray();}}public static NetworkMessage FromBytes(byte[] data){// 实现从字节数组解析报文using (var ms = new MemoryStream(data))using (var reader = new BinaryReader(ms)){var msg = new NetworkMessage();msg.Header = MessageHeader.FromBytes(reader.ReadBytes(MessageHeader.HEADER_LENGTH));msg.Body = reader.ReadBytes(msg.Header.Length);return msg;}}}
}

相关文章:

  • 变更管理 Change Management
  • 基于 Electron、Vue3 和 TypeScript 的辅助创作工具全链路开发方案:涵盖画布系统到数据持久化的完整实现
  • 【前端记事】关于electron的入门使用
  • Spring Boot 启动生命周期详解
  • 通俗的理解TCP的三次握手四次挥手
  • 高级java每日一道面试题-2025年4月21日-基础篇[反射篇]-如何使用反射获取一个类的所有方法?
  • Pikachu靶场-RCE漏洞
  • 三网通电玩城平台系统结构与源码工程详解(三):控制台与银商权限模块设计
  • Linux虚拟机中 编译Linux源码 记录
  • spark和Hadoop之间的对比与联系
  • wps批量修改字体
  • 当OCR遇上“幻觉”:如何让AI更靠谱地“看懂”文字?
  • 代码随想录第三十七天|华为秋季笔试真题230823
  • SpringbootWeb开发(注解和依赖配置)
  • 时序数据库IoTDB与OpenTSDB的对比分析
  • 卷积神经网络迁移学习:原理与实践指南
  • 实训Day-2 流量分析与安全杂项
  • 晶振详解:原理、作用、种类、应用与选型要点
  • Spring XML 配置
  • Selenium+Java 环境搭建
  • IMF将今年全球经济增长预期由3.3%下调至2.8%
  • 图忆|温州旅沪先贤的家国情怀
  • 特朗普“炮轰”美联储带崩美股!道指跌超900点,黄金再创新高
  • 经济日报刊文谈外卖平台仍试图凭补贴制造超低价:苦练内功摆脱“内卷式”竞争
  • 机器人马拉松背后的五大启示:未来社会与机器人的深度融合
  • 全球安全倡议提出三周年,外交部介绍有关情况