socket数据包及解码
建立数据包:
static Char start = (Char)0x0a;//开始标记
static Char end = (Char)0x1a;//结束符
static Char jG = (Char)0x09;
private Byte[] BuildContent()
{
int result = 1;
if (this._successful)
result = 0;
string content = this._index + jG + result + jG + this._msg;
return Encoding.ASCII.GetBytes(content);
}
public Byte[] ToByte()
{
int len = 0;
Byte startByte = Convert.ToByte(start);
len += 1;
len += 4;
Byte[] content = this.BuildContent();
len += content.Length;
Byte endByre = Convert.ToByte(end);
len += 1;
Char[] lengthChar = len.ToString().PadLeft(4, ' ').ToCharArray();
Byte[] lengthByte = new Byte[lengthChar.Length];
for (var i = 0; i < lengthChar.Length; i++)
{
lengthByte[i] = Convert.ToByte(lengthChar[i]);
}
Byte[] bs = new Byte[len];
bs[0] = startByte;
Array.Copy(lengthByte, 0, bs, 1, lengthByte.Length);
Array.Copy(content, 0, bs, 5, content.Length);
bs[len - 1] = endByre;
return bs;
}
解码:
public string[] Parse()
{
if (this._rd == null) return null;
string data = Encoding.ASCII.GetString(this._rd.Data,this._rd.Offset,this._rd.Length);
string temp = data.Split(start)[1].Split(end)[0].Trim();
string dataLength = this._rd.Length.ToString();
string strContent = temp.Substring(dataLength.Length, temp.Length - dataLength.Length);
string[] content = strContent.Split(jG);
return content;
}