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:(.*?)\r\n"); 12 Match m = reg.Match(handShakeText); 13 if (m.Value != "") 14 { 15 key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$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" + "\r\n"); 21 responseBuilder.Append("Upgrade: websocket" + "\r\n"); 22 responseBuilder.Append("Connection: Upgrade" + "\r\n"); 23 responseBuilder.Append("Sec-WebSocket-Accept: " + secKey + "\r\n\r\n"); 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