基于C#的通信协议封包

接上一篇《基于.NET技术的监控系统应用分析》中所描述的数据通信协议设计,我们来看一下在C#中是怎么对自定义协议进行封包的?我们知道基于流的数据协议的特点:发送和接收到的数据都是连续的流。每次网络I/O操作的流长度不确定,也就是无法知道每次接收到的数据是一个完整的数据包。同样,主机发送一个数据包也会根据网络的实际情况执行若干次。所以我们对这类消息的编解码过程需要进行一个统一的封装。

重新回顾一下每个消息的结构:消息头 + 消息体。每次先发送出去的是消息头,然后是消息体。消息头里描述了这个数据包的类型,长度,序列号等信息。消息头的长度是固定的,消息体的长度是根据每个消息类型会有所的区别。

消息头的定义:

字段

长度(字节)

类型

说明

Length

4

Int

消息的总长度(字节)

Command ID

4

Int

命令ID

NodeID

4

Int

结点ID

TimeID

4

Int

时间戳

SequenceID

4

Int

递增序列号

 

对应的封装代码:

using System;
using MonitorLib.Utility;

namespace MonitorLib.Protocol
{
/// <summary>
/// 消息头
/// </summary>
[Serializable]
public class Head
{
private byte[] initValue = new byte[Head.HeaderLength];

public Head(Command CommandID)
{
Converter.IntToBytes((uint)CommandID).CopyTo(initValue, 4);
}

public Head(byte[] bs)
{
uint length = Head.HeaderLength ;

for (int i = 0;i < length;i++)
{
initValue[i]=bs[i];
}
}


public Head(byte[] bs,int baseIndex)
{
uint length = Head.HeaderLength ;
for (int i = 0; i < length; i++)
{
initValue[i]=bs[baseIndex+i];
}
}

/// <summary>
/// 消息的整个长度
/// </summary>
public uint Length
{
get
{
return (Converter.BytesToUInt(initValue,0));
}
set
{
byte[] byt = Converter.IntToBytes(value);
for (int i = 0;i < 4;i++)
{
initValue[i]= byt[i];
}
}
}

/// <summary>
/// 命令类型
/// </summary>
public uint CommandID
{
get
{
return (Converter.BytesToUInt(initValue, 4));
}
set
{
byte[] t=Converter.IntToBytes(value);
for (int i = 0; i < 4; i++)
{
initValue[i + 4] = t[i];
}
}
}

/// <summary>
/// 源结点号
/// </summary>
public uint NodeID
{
get
{
return (Converter.BytesToUInt(initValue, 8));
}
set
{
byte[] t = Converter.IntToBytes(value);
for (int i = 0; i < 4; i++)
{
initValue[i + 8] = t[i];
}
}
}

/// <summary>
/// 时间戳
/// </summary>
public uint TimeID
{
get
{
return (Converter.BytesToUInt(initValue,12));
}
set
{
byte[] t = Converter.IntToBytes(value);
for (int i = 0; i < 4; i++)
{
initValue[i + 12] = t[i];
}
}
}

/// <summary>
/// 序列号
/// </summary>
public uint SequenceID
{
get
{
return (Converter.BytesToUInt(initValue,16));
}
set
{
byte[] t = Converter.IntToBytes(value);
for (int i = 0;i < 4;i++)
{
initValue[i + 16] = t[i];
}
}
}


/// <summary>
/// 输出字节流
/// </summary>
/// <returns></returns>
public byte[] ToBytes()
{
return initValue;
}

/// <summary>
/// 从字节流中转换
/// </summary>
/// <param name="bs"></param>
public void FromBytes(byte[] bs)
{
for (int i = 0; i < Head.HeaderLength; i++)
{
initValue[i] = bs[i];
}
}

/// <summary>
/// 消息头的长度
/// </summary>
public static uint HeaderLength
{
get
{
return (4 + 4 + 12);
}
}
}
}
using System;
using MonitorLib.Utility;

namespace MonitorLib.Protocol
{

/// <summary>
/// Sequence 的摘要说明。
/// </summary>
[Serializable]
public class Sequence
{
private uint node;
private uint time;
private uint sequence;
public Sequence()
{

}

public uint Node
{
get { return this.node; }
set { this.node = value; }
}

public uint Time
{
get { return this.time; }
set { this.time = value; }

}

public uint Value
{
get { return sequence; }
set { this.sequence = value; }
}

public ulong ToUInt64()
{
string temp = String.Format("{0}{1}{2}", Node, Time, Value);
return Convert.ToUInt64(temp);
}
}

public class Seed
{
private uint sequence = uint.MinValue;

public uint GetSequence()
{
lock (this)
{
return this.sequence >= 90000 ? uint.MinValue : this.sequence++;
}
}

public uint GetTimeStamp()
{
lock (this)
{
return Convert.ToUInt32(DateTime.Now.ToString("MMddHHmmss"));
}
}

}
}

上面只是一个消息头,要成为一个完整的消息,一般还必须包含消息体(当然你也可以根据需要仅发送一个消息头的数据,作为特殊用途,例如自定义的心跳包)。举个例子:客户机与服务器连接上后,它通常会发送一个绑定(Bind) 消息给服务器端。例如:验证确认客户端的合法性。那么此时的Bind消息的格式是:

 

字段

长度(字节)

类型

说明

HEAD

 

 

上面的消息头部

loginName

16

string

用户名(固定16位,不足用空格填充)

LoginPassword

16

string

密码(固定16位,不足用空格填充)

 

对应的封装代码:

using System;
using MonitorLib.Utility;

namespace MonitorLib.Protocol
{
/**/
/// <summary>
/// AbstractBase 的摘要说明。
/// </summary>

[Serializable]
public abstract class AbstractBase
{
protected byte[] initValue;
public Head header;

public AbstractBase()
{

}

public virtual byte[] ToBytes()
{
return null;
}
}
}
using System;
using System.IO;

namespace MonitorLib.Utility
{
/// <summary>
///消息命令常量
/// </summary>
public enum Command : uint
{
/// <summary>
/// 对客户端验证
/// </summary>
MOT_BIND = 0x1,

/// <summary>
/// 服务端返回验证请求
/// </summary>
MOT_BIND_RESP = 0x80000001,

/// <summary>
/// 断开连接
/// </summary>
MOT_UNBIND =0x2,

/// <summary>
/// 返回断开连接状态
/// </summary>
MOT_UNBIND_RESP=0x80000002,

/// <summary>
/// 上行提交内容
/// </summary>
MOT_SUBMIT = 0x3,

/// <summary>
/// submit 应答
/// </summary>
MOT_SUBMIT_RESP = 0x80000003,

/// <summary>
/// 设置命令
/// </summary>
MOT_REQUEST = 0x4,

MOT_REQUEST_RESP = 0x80000004,

/// <summary>
/// 连接命令
/// </summary>
MOT_CONNECT = 0x5,

MOT_CONNECT_RESP = 0x80000005,

/// <summary>
/// 更新程序命令
/// </summary>
MOT_UPDATE = 0x6,

MOT_UPDATE_RESP = 0x80000006,

/// <summary>
/// 返回结点的数据参数
/// </summary>
MOT_RESPONSE_PARAM = 0x7,

MOT_CLIENTINFO = 0x8,

MOT_CLIENTINFO_RESP = 0x80000008


}

/// <summary>
/// 错误定义
/// </summary>
public enum ErrorDefine : int
{
/// <summary>
///无错误,命令正确接收
/// </summary>
NO_ERROR = 0,

/// <summary>
/// 非法登录,如登录名、口令出错、登录名与口令不符等
/// </summary>
ILLEAGE_LOGIN = 1,

/// <summary>
/// 重复登录,如在同一TCP/IP连接中连续两次以上请求登录。
/// </summary>
REPEAT_LOGIN =2,

/// <summary>
/// 连接过多,指单个节点要求同时建立的连接数过多。
/// </summary>
MORE_CONNECT = 3,

/// <summary>
/// 不知道的用户
/// </summary>
UNKNOW_USER = 29,

/// <summary>
/// 不提供此功能
/// </summary>
UNSUPPORT_FUNCTION = 30,

/// <summary>
/// 系统失败
/// </summary>
SYSTEM_FAIL = 32,
}


/// <summary>
/// 字节 整形 转换类 网络格式转换为内存格式
/// </summary>
public class Converter
{
/// <summary>
/// 转换整形数据网络次序的字节数组
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public static byte[] IntToBytes(uint i)
{
byte[] t = BitConverter.GetBytes(i) ;
byte b = t[0];
t[0] = t[3];
t[3] = b;
b = t[1];
t[1] = t[2];
t[2] = b;
return (t);
}

public static byte[] IntToBytes(uint source,int number)
{
byte[] t = new byte[number];
t = BitConverter.GetBytes(source);
byte temp;
for (int i = t.Length-1; i > t.Length/2; i--)
{
temp = t[i];
t[i] = t[t.Length-1-i];
t[t.Length-1-i] = temp;
}
return (t);
}

/// <summary>
/// 返回字节数组代表的整数数字,4个数组
/// </summary>
/// <param name="bs"></param>
/// <param name="startIndex"></param>
/// <returns></returns>
public static uint BytesToUInt(byte[] bs,int startIndex)
{
byte[] t=new byte[4];
for (int i = 0; i < 4 && i < bs.Length-startIndex; i++)
{
t[i]=bs[startIndex+i];
}

byte b=t[0];
t[0]=t[3];
t[3]=b;
b=t[1];
t[1]=t[2];
t[2]=b;

return BitConverter.ToUInt32(t,0);
}

public static uint BytesToUInt(byte[] b,int startIndex,int number)
{
byte[] t = new Byte[number];
for (int i = 0; i < number && i < b.Length-startIndex; i++)
{
t[i] = b[startIndex+i];
}

byte temp;
for (int i = t.Length-1; i > t.Length/2; i--)
{
temp = t[i];
t[i]=t[t.Length-1-i];
t[i] = temp;
}
return (BitConverter.ToUInt32(t,0));
}

/// <summary>
/// 没有指定起始索引
/// </summary>
/// <param name="bs"></param>
/// <returns></returns>
public static uint BytesToUInt(byte[] bs)
{
return (BytesToUInt(bs,0));
}
}

/// <summary>
/// 缓冲区对象
/// </summary>
public class BufferObject
{
private byte[] buffer = null;
private int length = 0;

public BufferObject(byte[] bytes, int len)
{
if (buffer != null)
{
buffer = null;
GC.Collect();
}

length = len;
buffer = new byte[len];
for (int i = 0; i < len; i++)
{
buffer[i] = bytes[i];
}
}

public byte[] Buffer
{
get { return buffer;}
}

public int Length
{
get { return length; }
}
}
}

}
using System;
using System.Text;
using MonitorLib.Utility;

namespace MonitorLib.Protocol
{

/// <summary>
/// Bind消息
/// </summary>
[Serializable]
public class Bind : AbstractBase
{
private string loginName;
private string loginPassword;

/// <summary>
/// 初始Bind命令的消息头
/// </summary>
/// <param name="Sequence">序列号</param>
public Bind(Sequence seq)
{
header = new Head(Command.MOT_BIND);
header.NodeID = seq.Node;
header.TimeID = seq.Time;
header.SequenceID = seq.Value;
header.Length = Head.HeaderLength + 16 + 16;
}

public Bind(byte[] receive)
{
initValue = new byte[receive.Length];
receive.CopyTo(initValue, 0);
}

/// <summary>
/// 登录名
/// </summary>
public string LoginName
{
get
{
return Encoding.ASCII.GetString(initValue, 20, 16);
}
set
{
loginName = value;
}
}

/// <summary>
/// 密码
/// </summary>
public string LoginPassword
{
get
{
return Encoding.ASCII.GetString(initValue, 36, 16);
}
set
{
loginPassword = value;
}
}

/// <summary>
/// 把消息结构转换成字节数组
/// </summary>
/// <returns>结果字节数组</returns>
public override byte[] ToBytes()
{
byte[] retValue = new byte[this.header.Length];
uint index = 0;

//填充消息头
header.ToBytes().CopyTo(retValue, index);

index += Head.HeaderLength;
Encoding.ASCII.GetBytes(loginName).CopyTo(retValue, index);

//移位16位, 填充密码
index += 16;
Encoding.ASCII.GetBytes(loginPassword).CopyTo(retValue, index);
return retValue;
}
}

/// <summary>
/// Bind应答结构
/// </summary>
[Serializable]
public class Bind_Resp : AbstractBase
{
private uint result;

/// <summary>
/// 构造函数,把接收的字节数组复制到initValue
/// </summary>
/// <param name="recBytes">从网络上接收到的字节数组</param>
public Bind_Resp(byte[] receive)
{
initValue = new byte[receive.Length];
receive.CopyTo(initValue, 0);
}

public Bind_Resp(Sequence seq)
{
header = new Head(Command.MOT_BIND_RESP);
header.NodeID = seq.Node;
header.TimeID = seq.Time;
header.SequenceID = seq.Value;
header.Length = Head.HeaderLength + 4;
}

/// <summary>
/// bind 执行命令是否成功,0-成功。其它:错误码。
/// </summary>
public uint Result
{
get
{
return Convert.ToUInt32(initValue[20].ToString());
}
set
{
result = value;
}
}

public override byte[] ToBytes()
{
byte[] retValue = new byte[header.Length];
header.ToBytes().CopyTo(retValue, 0);
BitConverter.GetBytes(result).CopyTo(retValue, 20);
return retValue;
}
}

}

除了这种协议封装方法外,还有一种直接利用 .NET 的字节流操作类来编解码,例如 ICMP 协议的封包代码:

public class ICMPHDR 
{
private byte mType;
public byte Type
{
get{ return mType; }
set{ mType = value; }
}

private byte mCode = 0;
public byte Code
{
get{ return mCode; }
set{ mCode = value; }
}

private ushort mChecksum = 0;
public ushort Checksum
{
get{ return mChecksum; }
set{ mChecksum = value; }
}

private ushort mID;
public ushort ID
{
get{ return mID; }
set{ mID = value; }
}

private ushort mSeq;
public ushort Seq
{
get{ return mSeq; }
set{ mSeq = value; }
}

private ulong mtmSend;
public ulong tmSend
{
get{ return mtmSend; }
set{ mtmSend = value; }
}

private int mnTaskId;
public int nTaskId
{
get{ return mnTaskId; }
set{ mnTaskId = value; }
}

public void Encode(BinaryWriter writer)
{
writer.Write(Type);
writer.Write(Code);
writer.Write((UInt16)Checksum);
writer.Write((UInt16)ID);
writer.Write((UInt16)Seq);
writer.Write((UInt32)tmSend);
writer.Write(nTaskId);
}

public void Decode(BinaryReader reader)
{
Type = reader.ReadByte();
Code = reader.ReadByte();
Checksum = reader.ReadUInt16();
ID = reader.ReadUInt16();
Seq = reader.ReadUInt16();
tmSend = reader.ReadUInt32();
nTaskId = reader.ReadInt32();
}

public uint Sum()
{
uint sum = 0;
sum += (ushort)(Type + (Code << 8));
sum += (ushort)ID;
sum += (ushort)Seq;
sum += (ushort)tmSend;
sum += (ushort)(tmSend >> 16);
sum += (ushort)nTaskId;
sum += (ushort)(nTaskId >> 16);
return sum;
}
}
  以上介绍了用C#是如何对自定义的通信协议封装的过程。 如有不同的处理方法的朋友,欢迎评论,一起探讨一下。

 

freedom -
共有0个回答