webSocket浏览器握手不成功(解决)

 websocket与服务端握手会报握手不成功的错误解决方法:

首先是服务端首次收到请求要回报给客户端的报文要做处理多的不说,方法敬上:

 1  /// <summary>
 2         /// 打包请求连接数据
 3         /// </summary>
 4         /// <param name="handShakeBytes"></param>
 5         /// <param name="length"></param>
 6         /// <returns></returns>
 7         private byte[] PackageHandShakeData(byte[] handShakeBytes, int length)
 8         {
 9             string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, length);
10             string key = string.Empty;
11             Regex reg = new Regex(@"Sec-WebSocket-Key:(.*?)
");
12             Match m = reg.Match(handShakeText);
13             if (m.Value != "")
14             {
15                 key = Regex.Replace(m.Value, @"Sec-WebSocket-Key:(.*?)
", "$1").Trim();
16             }
17             byte[] secKeyBytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
18             string secKey = Convert.ToBase64String(secKeyBytes);
19             var responseBuilder = new StringBuilder();
20             responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + "
");
21             responseBuilder.Append("Upgrade: websocket" + "
");
22             responseBuilder.Append("Connection: Upgrade" + "
");
23             responseBuilder.Append("Sec-WebSocket-Accept: " + secKey + "

");
24             return Encoding.UTF8.GetBytes(responseBuilder.ToString());
25         }

当连接成功,你会发现客户端可以随意给服务器发送消息,但是服务器给客户端发送消息还是会断开连接这是因为报文的问题:

 1  /// <summary>
 2         /// 把发送给客户端消息打包处理
 3         /// </summary>
 4         /// <returns></returns>
 5         /// <param name="message">Message.</param>
 6         private byte[] SendMsg(string msg)
 7         {
 8             byte[] content = null;
 9             byte[] temp = Encoding.UTF8.GetBytes(msg);
10             if (temp.Length < 126)
11             {
12                 content = new byte[temp.Length + 2];
13                 content[0] = 0x81;
14                 content[1] = (byte)temp.Length;
15                 Buffer.BlockCopy(temp, 0, content, 2, temp.Length);
16             }
17             else if (temp.Length < 0xFFFF)
18             {
19                 content = new byte[temp.Length + 4];
20                 content[0] = 0x81;
21                 content[1] = 126;
22                 content[2] = (byte)(temp.Length & 0xFF);
23                 content[3] = (byte)(temp.Length >> 8 & 0xFF);
24                 Buffer.BlockCopy(temp, 0, content, 4, temp.Length);
25             }
26             return content;
27         }

完成之后就可以畅游通讯了!!

再次声明参考文献:http://www.cnblogs.com/smark/archive/2012/11/26/2789812.html

原文地址:https://www.cnblogs.com/yanbigfeg/p/7347072.html