SocketConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. using System.Text;
  2. using System.Net.Sockets;
  3. using System;
  4. using System.Security.Cryptography;
  5. namespace SocketSrv
  6. {
  7. //每一个客户端
  8. public class SocketConnection
  9. {
  10. // private Logger logger;
  11. private string name;
  12. private string id;
  13. public string Name
  14. {
  15. get { return name; }
  16. set { name = value; }
  17. }
  18. public string Id
  19. {
  20. get { return id; }
  21. set { id = value; }
  22. }
  23. private Boolean isDataMasked;
  24. public Boolean IsDataMasked
  25. {
  26. get { return isDataMasked; }
  27. set { isDataMasked = value; }
  28. }
  29. public Socket ConnectionSocket;
  30. private int MaxBufferSize;
  31. private string Handshake;
  32. private string New_Handshake;
  33. public byte[] receivedDataBuffer;
  34. private byte[] FirstByte;
  35. private byte[] LastByte;
  36. private byte[] ServerKey1;
  37. private byte[] ServerKey2;
  38. public event NewConnectionEventHandler NewConnection;
  39. public event DataReceivedEventHandler DataReceived;
  40. public event DisconnectedEventHandler Disconnected;
  41. public SocketConnection()
  42. {
  43. // logger = new Logger();
  44. MaxBufferSize = 1024*100;
  45. receivedDataBuffer = new byte[MaxBufferSize];
  46. FirstByte = new byte[MaxBufferSize];
  47. LastByte = new byte[MaxBufferSize];
  48. FirstByte[0] = 0x00;
  49. LastByte[0] = 0xFF;
  50. Handshake = "HTTP/1.1 101 Web Socket Protocol Handshake" + Environment.NewLine;
  51. Handshake += "Upgrade: WebSocket" + Environment.NewLine;
  52. Handshake += "Connection: Upgrade" + Environment.NewLine;
  53. Handshake += "Sec-WebSocket-Origin: " + "{0}" + Environment.NewLine;
  54. Handshake += string.Format("Sec-WebSocket-Location: " + "ws://{0}:4141/chat" + Environment.NewLine, "192.168.0.102");
  55. Handshake += Environment.NewLine;
  56. New_Handshake = "HTTP/1.1 101 Switching Protocols" + Environment.NewLine;
  57. New_Handshake += "Upgrade: WebSocket" + Environment.NewLine;
  58. New_Handshake += "Connection: Upgrade" + Environment.NewLine;
  59. New_Handshake += "Sec-WebSocket-Accept: {0}" + Environment.NewLine;
  60. New_Handshake += Environment.NewLine;
  61. }
  62. //客户端监听方法
  63. private void Read(IAsyncResult status)
  64. {
  65. if (!ConnectionSocket.Connected) return;
  66. string messageReceived = string.Empty;
  67. DataFrame dr = new DataFrame(receivedDataBuffer);
  68. try
  69. {
  70. if (!this.isDataMasked)
  71. {
  72. // Web Socket protocol: messages are sent with 0x00 and 0xFF as padding bytes
  73. System.Text.UTF8Encoding decoder = new System.Text.UTF8Encoding();
  74. int startIndex = 0;
  75. int endIndex = 0;
  76. // Search for the start byte
  77. while (receivedDataBuffer[startIndex] == FirstByte[0]) startIndex++;
  78. // Search for the end byte
  79. endIndex = startIndex + 1;
  80. while (receivedDataBuffer[endIndex] != LastByte[0] && endIndex != MaxBufferSize - 1) endIndex++;
  81. if (endIndex == MaxBufferSize - 1) endIndex = MaxBufferSize;
  82. // Get the message
  83. messageReceived = decoder.GetString(receivedDataBuffer, startIndex, endIndex - startIndex);
  84. }
  85. else
  86. {
  87. messageReceived = dr.Text;
  88. }
  89. if ((messageReceived.Length == MaxBufferSize && messageReceived[0] == Convert.ToChar(65533)) ||
  90. messageReceived.Length == 0)
  91. {
  92. //断开连接
  93. //logger.Log("接受到的信息 [\"" + string.Format("logout:{0}",this.name) + "\"]");
  94. if (Disconnected != null)
  95. Disconnected(this, EventArgs.Empty);
  96. }
  97. else
  98. {
  99. if (messageReceived.IndexOf("login:") != -1)
  100. {
  101. //新用户登录
  102. // logger.Log("接受到的信息 [\"" + messageReceived + "\"]");
  103. NewConnection(this, messageReceived, EventArgs.Empty);
  104. }
  105. else
  106. {
  107. if (DataReceived != null)
  108. {
  109. //消息转发
  110. // logger.Log("接受到的信息 [\"" + messageReceived + "\"]");
  111. DataReceived(this, messageReceived, EventArgs.Empty);
  112. }
  113. }
  114. Array.Clear(receivedDataBuffer, 0, receivedDataBuffer.Length);
  115. ConnectionSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);
  116. }
  117. }
  118. catch(Exception ex)
  119. {
  120. //logger.Log(ex.Message);
  121. //logger.Log("Socket连接将会被终止。");
  122. if (Disconnected != null)
  123. Disconnected(this, EventArgs.Empty);
  124. }
  125. }
  126. private void BuildServerPartialKey(int keyNum, string clientKey)
  127. {
  128. string partialServerKey = "";
  129. byte[] currentKey;
  130. int spacesNum = 0;
  131. char[] keyChars = clientKey.ToCharArray();
  132. foreach (char currentChar in keyChars)
  133. {
  134. if (char.IsDigit(currentChar)) partialServerKey += currentChar;
  135. if (char.IsWhiteSpace(currentChar)) spacesNum++;
  136. }
  137. try
  138. {
  139. currentKey = BitConverter.GetBytes((int)(Int64.Parse(partialServerKey) / spacesNum));
  140. if (BitConverter.IsLittleEndian) Array.Reverse(currentKey);
  141. if (keyNum == 1) ServerKey1 = currentKey;
  142. else ServerKey2 = currentKey;
  143. }
  144. catch
  145. {
  146. if (ServerKey1 != null) Array.Clear(ServerKey1, 0, ServerKey1.Length);
  147. if (ServerKey2 != null) Array.Clear(ServerKey2, 0, ServerKey2.Length);
  148. }
  149. }
  150. private byte[] BuildServerFullKey(byte[] last8Bytes)
  151. {
  152. byte[] concatenatedKeys = new byte[16];
  153. Array.Copy(ServerKey1, 0, concatenatedKeys, 0, 4);
  154. Array.Copy(ServerKey2, 0, concatenatedKeys, 4, 4);
  155. Array.Copy(last8Bytes, 0, concatenatedKeys, 8, 8);
  156. // MD5 Hash
  157. System.Security.Cryptography.MD5 MD5Service = System.Security.Cryptography.MD5.Create();
  158. return MD5Service.ComputeHash(concatenatedKeys);
  159. }
  160. public void ManageHandshake(IAsyncResult status)
  161. {
  162. string header = "Sec-WebSocket-Version:";
  163. int HandshakeLength = (int)status.AsyncState;
  164. byte[] last8Bytes = new byte[8];
  165. System.Text.UTF8Encoding decoder = new System.Text.UTF8Encoding();
  166. String rawClientHandshake = decoder.GetString(receivedDataBuffer, 0, HandshakeLength);
  167. Array.Copy(receivedDataBuffer, HandshakeLength - 8, last8Bytes, 0, 8);
  168. //现在使用的是比较新的Websocket协议
  169. if (rawClientHandshake.IndexOf(header) != -1)
  170. {
  171. this.isDataMasked = true;
  172. string[] rawClientHandshakeLines = rawClientHandshake.Split(new string[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries);
  173. string acceptKey = "";
  174. foreach (string Line in rawClientHandshakeLines)
  175. {
  176. Console.WriteLine(Line);
  177. if (Line.Contains("Sec-WebSocket-Key:"))
  178. {
  179. acceptKey = ComputeWebSocketHandshakeSecurityHash09(Line.Substring(Line.IndexOf(":") + 2));
  180. }
  181. }
  182. New_Handshake = string.Format(New_Handshake, acceptKey);
  183. byte[] newHandshakeText = Encoding.UTF8.GetBytes(New_Handshake);
  184. ConnectionSocket.BeginSend(newHandshakeText, 0, newHandshakeText.Length, 0, HandshakeFinished, null);
  185. return;
  186. }
  187. string ClientHandshake = decoder.GetString(receivedDataBuffer, 0, HandshakeLength - 8);
  188. string[] ClientHandshakeLines = ClientHandshake.Split(new string[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries);
  189. // logger.Log("新的连接请求来自" + ConnectionSocket.LocalEndPoint + "。正在准备连接 ...");
  190. // Welcome the new client
  191. foreach (string Line in ClientHandshakeLines)
  192. {
  193. // logger.Log(Line);
  194. if (Line.Contains("Sec-WebSocket-Key1:"))
  195. BuildServerPartialKey(1, Line.Substring(Line.IndexOf(":") + 2));
  196. if (Line.Contains("Sec-WebSocket-Key2:"))
  197. BuildServerPartialKey(2, Line.Substring(Line.IndexOf(":") + 2));
  198. if (Line.Contains("Origin:"))
  199. try
  200. {
  201. Handshake = string.Format(Handshake, Line.Substring(Line.IndexOf(":") + 2));
  202. }
  203. catch
  204. {
  205. Handshake = string.Format(Handshake, "null");
  206. }
  207. }
  208. // Build the response for the client
  209. byte[] HandshakeText = Encoding.UTF8.GetBytes(Handshake);
  210. byte[] serverHandshakeResponse = new byte[HandshakeText.Length + 16];
  211. byte[] serverKey = BuildServerFullKey(last8Bytes);
  212. Array.Copy(HandshakeText, serverHandshakeResponse, HandshakeText.Length);
  213. Array.Copy(serverKey, 0, serverHandshakeResponse, HandshakeText.Length, 16);
  214. // logger.Log("发送握手信息 ...");
  215. ConnectionSocket.BeginSend(serverHandshakeResponse, 0, HandshakeText.Length + 16, 0, HandshakeFinished, null);
  216. // logger.Log(Handshake);
  217. }
  218. public static String ComputeWebSocketHandshakeSecurityHash09(String secWebSocketKey)
  219. {
  220. const String MagicKEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  221. String secWebSocketAccept = String.Empty;
  222. // 1. Combine the request Sec-WebSocket-Key with magic key.
  223. String ret = secWebSocketKey + MagicKEY;
  224. // 2. Compute the SHA1 hash
  225. SHA1 sha = new SHA1CryptoServiceProvider();
  226. byte[] sha1Hash = sha.ComputeHash(Encoding.UTF8.GetBytes(ret));
  227. // 3. Base64 encode the hash
  228. secWebSocketAccept = Convert.ToBase64String(sha1Hash);
  229. return secWebSocketAccept;
  230. }
  231. private void HandshakeFinished(IAsyncResult status)
  232. {
  233. ConnectionSocket.EndSend(status);
  234. ConnectionSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);
  235. // if (NewConnection != null) NewConnection("", EventArgs.Empty);
  236. }
  237. }
  238. }