//数据帧的解析代码:
static string byteToString(byte[] buffer, int count, Socket client)
{
int type = buffer[0] & 0xF;
if (type == 0x1) //文本
{
int mask = buffer[1] & 0x80;
int len = buffer[1] & 0x7f;
int dataLen = 0;
int index = 2;
if (len < 126)
{
dataLen = len;
}
else if (len == 126)
{
//+2
ByteToshort(ref dataLen, buffer);
index += 2;
}
else
{
//+4
ByteToint(ref dataLen, buffer);
index += 4;
}
byte[] mark_Key = new byte[4];
if (mask == 0x80)
{
mark_Key = new byte[] { buffer[index], buffer[index + 1], buffer[index + 2], buffer[index + 3] };
index += 4;
}
if (count >= dataLen + index)
{
byte[] real_Data = buffer.ToList().Skip(index).ToList().ToArray();
if (mask == 0x80)
{
for (int i = 0; i < real_Data.Length; i++)
{
real_Data[i] = (byte)(mark_Key[i % 4] ^ real_Data[i]);
}
}
Console.WriteLine("receive All: " + Encoding.UTF8.GetString(real_Data, 0, dataLen));
//剩余数据
}
else
{
//超长字段 不足
//byte[] data_all = new byte[dataLen];
//byte[] temp = new byte[1024];
//count = client.Receive(temp, SocketFlags.None);
//if (count > 0)
//{
// decodeDataFrame(temp, count, client);
//}
}
}
return null;
}
static void ByteToshort(ref int len, byte[] result)
{
len += (int)((result[2] << 8));
len += (int)((result[3]));
}
static void ByteToint(ref int len, byte[] result)
{
len += (int)((result[2] << 24));
len += (int)((result[3] << 16));
len += (int)((result[4] << 8));
len += (int)((result[5]));
}
//数据帧的编码: 服务器发送客户端不加密
static byte[] StringToByte(string msg)
{
byte[] data = Encoding.UTF8.GetBytes(msg);
List list = new List();
byte mask = 0x0; //0x80;
list.Add(0x80 | 0x1); // 0x80文本类型
if (data.Length < 126)
{
list.Add((byte)(mask | data.Length));
}
else if (data.Length >= 126 && data.Length <= 65535) // 126==7e 65535==ffff
{
list.Add((byte)(mask | 126));
list.AddRange(shortToByte(data.Length));
}
else
{
list.Add((byte)(mask | 127));
list.AddRange(intToByte(data.Length));
}
if (mask == 0x80)
{
byte[] mark_Key = new byte[] { 0x1, 0x2, 0x3, 0x4 };
for (int i = 0; i < data.Length; i++)
{
data[i] = (byte)(mark_Key[i % 4] ^ data[i]);
}
list.AddRange(mark_Key);
}
list.AddRange(data);
return list.ToArray();
}
static byte[] shortToByte(int len)
{
byte[] result = new byte[2];
//Console.WriteLine((len >> 8) & 0xff);
//Console.WriteLine(( 8) & 0xff);
result[0] = (byte)((len >> 8) & 0xff);
result[1] = (byte)((len) & 0xff);
return result;
}
static byte[] intToByte(int len)
{
byte[] result = new byte[4];
result[0] = (byte)((len >> 24) & 0xff);
result[1] = (byte)((len >> 16) & 0xff);
result[2] = (byte)((len >> 8) & 0xff);
result[3] = (byte)((len) & 0xff);
return result;
}