DBMNG数据库管理与应用

书籍是全世界的营养品。生活里没有书籍,就好像没有阳光;智慧里没有书籍,就好像鸟儿没有翅膀。
当前位置:首页 > 经验分享 > HTML5

WebSocket简单使用(四) - 完整实例

说是完整的实例,其实并不完整,这里需要说明,这个实例并没有实现并发,也没考虑到算法和资源管理,所谓的完整是有客户端和服务器端,并且能跑起来演示。直接上菜,关于理论请看前面三篇博文,TCP请另看相关知识。

客户端代码:

  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>Web sockets test</title>
  5. <script src="jquery-min.js" type="text/javascript"></script>
  6. <script type="text/javascript">
  7. var ws;
  8. function ToggleConnectionClicked() {
  9. try {
  10. ws = new WebSocket("ws://10.9.146.31:1818/chat");//连接服务器
  11. ws.onopen = function(event){alert("已经与服务器建立了连接\r\n当前连接状态:"+this.readyState);};
  12. ws.onmessage = function(event){alert("接收到服务器发送的数据:\r\n"+event.data);};
  13. ws.onclose = function(event){alert("已经与服务器断开连接\r\n当前连接状态:"+this.readyState);};
  14. ws.onerror = function(event){alert("WebSocket异常!");};
  15. } catch (ex) {
  16. alert(ex.message);
  17. }
  18. };
  19.  
  20. function SendData() {
  21. try{
  22. ws.send("beston");
  23. }catch(ex){
  24. alert(ex.message);
  25. }
  26. };
  27.  
  28. function seestate(){
  29. alert(ws.readyState);
  30. }
  31. </script>
  32. </head>
  33. <body>
  34. <button id='ToggleConnection' type="button" onclick='ToggleConnectionClicked();'>连接服务器</button><br /><br />
  35. <button id='ToggleConnection' type="button" onclick='SendData();'>发送我的名字:beston</button><br /><br />
  36. <button id='ToggleConnection' type="button" onclick='seestate();'>查看状态</button><br /><br />
  37. </body>
  38. </html>
服务器端代码:
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7.  
  8. namespace WebSocket
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. int port = 1818;
  15. byte[] buffer = new byte[1024];
  16.  
  17. IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
  18. Socket listener = new Socket(localEP.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
  19. try{
  20. listener.Bind(localEP);
  21. listener.Listen(10);
  22.  
  23. Console.WriteLine("等待客户端连接....");
  24. Socket sc = listener.Accept();//接受一个连接
  25. Console.WriteLine("接受到了客户端:"+sc.RemoteEndPoint.ToString()+"连接....");
  26. //握手
  27. int length = sc.Receive(buffer);//接受客户端握手信息
  28. sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer,length)));
  29. Console.WriteLine("已经发送握手协议了....");
  30. //接受客户端数据
  31. Console.WriteLine("等待客户端数据....");
  32. length = sc.Receive(buffer);//接受客户端信息
  33. string clientMsg=AnalyticData(buffer, length);
  34. Console.WriteLine("接受到客户端数据:" + clientMsg);
  35.  
  36. //发送数据
  37. string sendMsg = "您好," + clientMsg;
  38. Console.WriteLine("发送数据:“"+sendMsg+"” 至客户端....");
  39. sc.Send(PackData(sendMsg));
  40. Console.WriteLine("演示Over!");
  41.  
  42. }
  43. catch (Exception e)
  44. {
  45. Console.WriteLine(e.ToString());
  46. }
  47. }
  48.  
  49. /// <summary>
  50. /// 打包握手信息
  51. /// </summary>
  52. /// <param name="secKeyAccept">Sec-WebSocket-Accept</param>
  53. /// <returns>数据包</returns>
  54. private static byte[] PackHandShakeData(string secKeyAccept)
  55. {
  56. var responseBuilder = new StringBuilder();
  57. responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
  58. responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
  59. responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
  60. responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);
  61. //如果把上一行换成下面两行,才是thewebsocketprotocol-17协议,但居然握手不成功,目前仍没弄明白!
  62. //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);
  63. //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);
  64.  
  65. return Encoding.UTF8.GetBytes(responseBuilder.ToString());
  66. }
  67.  
  68. /// <summary>
  69. /// 生成Sec-WebSocket-Accept
  70. /// </summary>
  71. /// <param name="handShakeText">客户端握手信息</param>
  72. /// <returns>Sec-WebSocket-Accept</returns>
  73. private static string GetSecKeyAccetp(byte[] handShakeBytes,int bytesLength)
  74. {
  75. string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
  76. string key = string.Empty;
  77. Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
  78. Match m = r.Match(handShakeText);
  79. if (m.Groups.Count != 0)
  80. {
  81. key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
  82. }
  83. byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
  84. return Convert.ToBase64String(encryptionString);
  85. }
  86.  
  87. /// <summary>
  88. /// 解析客户端数据包
  89. /// </summary>
  90. /// <param name="recBytes">服务器接收的数据包</param>
  91. /// <param name="recByteLength">有效数据长度</param>
  92. /// <returns></returns>
  93. private static string AnalyticData(byte[] recBytes, int recByteLength)
  94. {
  95. if (recByteLength < 2) { return string.Empty; }
  96.  
  97. bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧
  98. if (!fin){
  99. return string.Empty;// 超过一帧暂不处理
  100. }
  101.  
  102. bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码
  103. if (!mask_flag){
  104. return string.Empty;// 不包含掩码的暂不处理
  105. }
  106.  
  107. int payload_len = recBytes[1] & 0x7F; // 数据长度
  108.  
  109. byte[] masks = new byte[4];
  110. byte[] payload_data;
  111.  
  112. if (payload_len == 126){
  113. Array.Copy(recBytes, 4, masks, 0, 4);
  114. payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);
  115. payload_data = new byte[payload_len];
  116. Array.Copy(recBytes, 8, payload_data, 0, payload_len);
  117.  
  118. }else if (payload_len == 127){
  119. Array.Copy(recBytes, 10, masks, 0, 4);
  120. byte[] uInt64Bytes = new byte[8];
  121. for (int i = 0; i < 8; i++){
  122. uInt64Bytes[i] = recBytes[9 - i];
  123. }
  124. UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);
  125.  
  126. payload_data = new byte[len];
  127. for (UInt64 i = 0; i < len; i++){
  128. payload_data[i] = recBytes[i + 14];
  129. }
  130. }else{
  131. Array.Copy(recBytes, 2, masks, 0, 4);
  132. payload_data = new byte[payload_len];
  133. Array.Copy(recBytes, 6, payload_data, 0, payload_len);
  134.  
  135. }
  136.  
  137. for (var i = 0; i < payload_len; i++){
  138. payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);
  139. }
  140. return Encoding.UTF8.GetString(payload_data);
  141. }
  142.  
  143.  
  144. /// <summary>
  145. /// 打包服务器数据
  146. /// </summary>
  147. /// <param name="message">数据</param>
  148. /// <returns>数据包</returns>
  149. private static byte[] PackData(string message)
  150. {
  151. byte[] contentBytes = null;
  152. byte[] temp = Encoding.UTF8.GetBytes(message);
  153.  
  154. if (temp.Length < 126){
  155. contentBytes = new byte[temp.Length + 2];
  156. contentBytes[0] = 0x81;
  157. contentBytes[1] = (byte)temp.Length;
  158. Array.Copy(temp, 0, contentBytes, 2, temp.Length);
  159. }else if (temp.Length < 0xFFFF){
  160. contentBytes = new byte[temp.Length + 4];
  161. contentBytes[0] = 0x81;
  162. contentBytes[1] = 126;
  163. contentBytes[2] = (byte)(temp.Length & 0xFF);
  164. contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
  165. Array.Copy(temp, 0, contentBytes, 4, temp.Length);
  166. }else{
  167. // 暂不处理超长内容
  168. }
  169.  
  170. return contentBytes;
  171. }
  172. }
  173. }
运行效果:

使用的浏览器:

下载代码:WebSocket.zip

疑问:如实例中

  1. responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);
  2. //如果把上一行换成下面两行,才是thewebsocketprotocol-17协议,但居然握手不成功,目前仍没弄明白!
  3. //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);
  4. //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);
这是为什么呢?看到这篇博文的兄弟希望能够给我解惑!
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号