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
}
}