Common.cs
3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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;
}
}
}
}