///
/// 消息包
/// 内存布局
/// {
/// short PacketFlag;//特殊的值
/// short PacketLength;//消息包的大小,消息不能大于32k
/// int PacketID;//消息包类型id;从这以后的数据可以加密
/// int SerialNumber;//消息包序列号,网络连接每发一个消息包,这个值+1
/// int DispatcherID;//发送者的id
/所以消息头的大小是2+2+4+4+4 = 16
/// }
///
public classPacket
{public const short MaxLength = 32000;//32k
public const short InvalidLength = -1;public const short NeedCompressMinLength = 100;public const short NoCryptHeaderLength = 4; //2+2//消息包标志
public PacketFlag PacketFlag =PacketFlag.Normal;public intPacketID;///
/// 消息序列号
///
public intSerialNumber;public int DispatcherID;//if id <0 ,is -serverid
protectedPacketWriter m_writer;public Packet(intpacketID)
:this(packetID,0)
{
}public Packet(int packetID,intdispatcherid)
{
PacketID=packetID;
DispatcherID=dispatcherid;
m_writer= new PacketWriter();/*PacketWriter.CreateInstance()*/;
}private byte[] m_databuffer; //已经有的数据的缓冲
private int m_datalength; //已经有的数据的大小
///
/// 消息总长度
///
public intLength
{
get{if (m_databuffer == null)return Packet.HeaderSize +m_writer.Length;else
return m_datalength +m_writer.Length;
}
set{if (m_databuffer == null)return;
m_datalength=value;
}
}
internalbyte[] DataBuffer{
get{returnm_databuffer;
}
set{
m_databuffer=value;if (m_databuffer != null)
m_datalength=m_databuffer.Length;
}
}publicPacketWriter Writer{
get{returnm_writer;
}
}
internal virtualbyte[] ToArray()
{short packet_length = (short)this.Length;
bool needcreatebuffer= false;if (DataBuffer == null || m_writer.Length > 0)
needcreatebuffer= true;if(needcreatebuffer)
{byte[] newbuffer = new byte[packet_length];if (m_databuffer != null)
{
Buffer.BlockCopy(m_databuffer,0, newbuffer, 0, m_datalength);
}
m_databuffer=newbuffer;
}//写消息头//ArrayUtility.SetShort(m_databuffer, (short)PacketFlag, 0);//ArrayUtility.SetShort(m_databuffer, packet_length, 2);//ArrayUtility.SetInt(m_databuffer, this.PacketID, 4);//ArrayUtility.SetInt(m_databuffer, this.SerialNumber, 8);//ArrayUtility.SetInt(m_databuffer, this.DispatcherID, 12);
WriteHead();if (needcreatebuffer && m_writer.Length > 0)
{
System.Buffer.BlockCopy(m_writer.ToArray(),0, m_databuffer,
packet_length-m_writer.Length, m_writer.Length);
m_writer.Length= 0;
}
m_datalength=packet_length;returnm_databuffer;
}protected voidWriteHead()
{//写消息头
ArrayUtility.SetShort(m_databuffer, (short)PacketFlag, 0);
ArrayUtility.SetShort(m_databuffer, (short)this.Length, 2);
ArrayUtility.SetInt(m_databuffer,this.PacketID, 4);
ArrayUtility.SetInt(m_databuffer,this.SerialNumber, 8);
ArrayUtility.SetInt(m_databuffer,this.DispatcherID, 12);
}///
/// 消息头大小 2+2+4+4+4 = 16
///
public static intHeaderSize
{
get
{return 16;
}
}public voidReset()
{
DataBuffer= null;
Writer.Clear();
}
}