SocketConnection.cs 11 KB

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