using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions; namespace LaiHuaRendSpeederServer
{
public static class WebSocketSeverHelper
{
/// <summary>
/// 打包服务器握手数据
/// </summary>
public static byte[] PackageHandShakeData(string handShakeText)
{
//string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, length);
string key = string.Empty;
Regex reg = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
Match m = reg.Match(handShakeText);
if (m.Value != "")
{
key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
} byte[] secKeyBytes = SHA1.Create().ComputeHash(
Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
string secKey = Convert.ToBase64String(secKeyBytes); var responseBuilder = new StringBuilder();
responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
responseBuilder.Append("Sec-WebSocket-Accept: " + secKey + Environment.NewLine + Environment.NewLine);
//responseBuilder.Append("Sec-WebSocket-Protocol: " + "chat, superchat" + Environment.NewLine + Environment.NewLine); return Encoding.UTF8.GetBytes(responseBuilder.ToString());
} /// <summary>
/// 解析客户端发送来的数据
/// </summary>
public static string DecodeClientData(byte[] recBytes, int length)
{
if (length < )
{
return string.Empty;
} bool fin = (recBytes[] & 0x80) == 0x80; //0x80 = 1000,0000 第1bit = 1表示最后一帧
if (!fin)
{
if (recBytes[] == 0xff)
{
}
else
return string.Empty;
} bool mask_flag = (recBytes[] & 0x80) == 0x80; // 是否包含掩码
if (!mask_flag)
{
return string.Empty;// 不包含掩码的暂不处理
} int payload_len = recBytes[] & 0x7F; // 数据长度 byte[] masks = new byte[];
byte[] payload_data; if (payload_len == )
{
Array.Copy(recBytes, , masks, , );
payload_len = (UInt16)(recBytes[] << | recBytes[]);
payload_data = new byte[payload_len];
Array.Copy(recBytes, , payload_data, , payload_len); }
else if (payload_len == )
{
Array.Copy(recBytes, , masks, , );
byte[] uInt64Bytes = new byte[];
for (int i = ; i < ; i++)
{
uInt64Bytes[i] = recBytes[ - i];
}
UInt64 len = BitConverter.ToUInt64(uInt64Bytes, ); payload_data = new byte[len];
for (UInt64 i = ; i < len; i++)
{
payload_data[i] = recBytes[i + ];
}
}
else
{
Array.Copy(recBytes, , masks, , );
payload_data = new byte[payload_len];
Array.Copy(recBytes, , payload_data, , payload_len); } for (var i = ; i < payload_len; i++)
{
payload_data[i] = (byte)(payload_data[i] ^ masks[i % ]);
}
//var uuu = new byte[payload_data.Length * 3 / 4];
//for (int i = 0; i < uuu.Length; i++)
//{
// uuu[i] = payload_data[i];
//}
//Console.WriteLine("UUUUUU:" + Encoding.UTF8.GetString(uuu));
return Encoding.UTF8.GetString(payload_data);
} public static byte[] DecodeClientByteData(byte[] recBytes, int length)
{
if (length < )
{
return null;
} bool fin = (recBytes[] & 0x80) == 0x80; //0x80 = 1000,0000 第1bit = 1表示最后一帧
//if (!fin)
//{
// if (recBytes[1] == 0xff)
// {
// if (recBytes[0] == 0x01)
// {
// recBytes[0] += 0x80;
// }
// else
// return null;
// }
// else
// return null;
//} bool mask_flag = (recBytes[] & 0x80) == 0x80; // 是否包含掩码
if (!mask_flag)
{
return null;// 不包含掩码的暂不处理
} int payload_len = recBytes[] & 0x7F; // 数据长度 byte[] masks = new byte[];
byte[] payload_data; if (payload_len == )
{
Array.Copy(recBytes, , masks, , );
payload_len = (UInt16)(recBytes[] << | recBytes[]);
payload_data = new byte[payload_len];
Array.Copy(recBytes, , payload_data, , payload_len); }
else if (payload_len == )
{
Array.Copy(recBytes, , masks, , );
byte[] uInt64Bytes = new byte[];
for (int i = ; i < ; i++)
{
uInt64Bytes[i] = recBytes[ - i];
}
UInt64 len = BitConverter.ToUInt64(uInt64Bytes, ); payload_data = new byte[len]; for (UInt64 i = ; i < len; i++)
{
payload_data[i] = recBytes[i + ];
}
}
else
{
Array.Copy(recBytes, , masks, , );
payload_data = new byte[payload_len];
Array.Copy(recBytes, , payload_data, , payload_len); } for (var i = ; i < payload_data.Length; i++)
{
payload_data[i] = (byte)(payload_data[i] ^ masks[i % ]);
}
return payload_data;
} /// <summary>
/// 把客户端消息打包处理
/// </summary>
public static byte[] EncodeServerData(string msg)
{ byte[] content = null;
byte[] temp = Encoding.UTF8.GetBytes(msg); if (temp.Length < )
{
content = new byte[temp.Length + ];
content[] = 0x81;
content[] = (byte)temp.Length;
Array.Copy(temp, , content, , temp.Length);
}
else if (temp.Length < 0xFFFF)
{
content = new byte[temp.Length + ];
content[] = 0x81;
content[] = ;
content[] = (byte)(temp.Length & 0xFF);
content[] = (byte)(temp.Length >> & 0xFF);
Array.Copy(temp, , content, , temp.Length);
}
else
{
// 暂不处理超长内容
}
return content;
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text; namespace LaiHuaRendSpeederServer
{
public static class WebSocketExt
{
public static int SendProtocol(this Socket s, Protocol p)
{
var msg = JsonConvert.SerializeObject(p);
Console.WriteLine("SendProtocol : " + msg);
return s.Send(WebSocketSeverHelper.EncodeServerData(msg));
}
public static int ReceiveProtocol(this Socket s, ref Protocol p)
{
byte[] buffer = new byte[];
int reccount = ;
List<ArraySegment<byte>> segList = new List<ArraySegment<byte>>();
if (s.Connected)
{
reccount = s.Receive(buffer);
if(reccount == )
{
s.Shutdown(SocketShutdown.Send);
p = null;
return ;
}
}
byte[] r = new byte[reccount];
Array.Copy(buffer, r, reccount);
buffer = null;
string mgs = string.Empty;
if ((r[] & 0x80) == )
{
segList.Add(new ArraySegment<byte>(r, , reccount));
byte[] r2 = new byte[];
while ((r2[] & 0x80) == )
{
r2 = new byte[];
int cout = s.Receive(r2);
segList.Add(new ArraySegment<byte>(r2, , cout));
}
byte[] all = null;
for (int i = ; i < segList.Count; i++)
{
if (all == null)
{
all = WebSocketSeverHelper.DecodeClientByteData(segList[i].Array, segList[i].Count);
}
else
{
var pit = WebSocketSeverHelper.DecodeClientByteData(segList[i].Array, segList[i].Count);
all = all.Concat(pit).ToArray();
}
}
mgs = Encoding.UTF8.GetString(all);
}
else
{
mgs = WebSocketSeverHelper.DecodeClientData(r, r.Length);
} if (mgs.Length < )
{
Console.WriteLine("ReceiveProtocol : " + mgs);
}
else
{
Console.WriteLine("ReceiveProtocol : " + mgs.Substring(, ));
}
try
{
var f = mgs.Substring(, mgs.Length - );
var menbs = f.Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
if (menbs.Length != )
{
p = null;
return reccount;
}
p = new Protocol();
foreach (var item in menbs)
{
var pare = item.Split(new string[] { "\":\"" }, StringSplitOptions.None);
if (pare.Length != )
{
p = null;
return reccount;
}
switch (pare[].Replace("\"", ""))
{
case "Head":
p.Head = pare[].Replace("\"", "");
break;
case "Func":
p.Func = pare[].Replace("\"", "");
break;
case "Name":
p.Name = pare[].Replace("\"", "");
break;
case "Data":
p.Data = pare[].Replace("\"", "");
break;
default:
p = null;
return reccount;
break;
}
}
//p = JsonConvert.DeserializeObject<Protocol>(mgs);
}
catch (Exception ex)
{
var errormsg = JsonConvert.SerializeObject(
new Protocol() { Func = FUNC.ERROR, Data = ex.ToString() });
if (s.Connected)
{
s.Send(WebSocketSeverHelper.EncodeServerData(errormsg));
}
Console.WriteLine("ERROR : " + errormsg);
s.Close();
}
return reccount;
}
}
}