
websocket与服务端握手会报握手不成功的错误解决方法:
首先是服务端首次收到请求要回报给客户端的报文要做处理多的不说,方法敬上:
/// <summary>
/// 打包请求连接数据
/// </summary>
/// <param name="handShakeBytes"></param>
/// <param name="length"></param>
/// <returns></returns>
private byte[] PackageHandShakeData(byte[] handShakeBytes, int length)
{
string handShakeText = Encoding.UTF8.GetString(handShakeBytes, , length);
string key = string.Empty;
Regex reg = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
Match m = reg.Match(handShakeText);
if (m.Value != "")
{
key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
}
byte[] secKeyBytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
string secKey = Convert.ToBase64String(secKeyBytes);
var responseBuilder = new StringBuilder();
responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + "\r\n");
responseBuilder.Append("Upgrade: websocket" + "\r\n");
responseBuilder.Append("Connection: Upgrade" + "\r\n");
responseBuilder.Append("Sec-WebSocket-Accept: " + secKey + "\r\n\r\n");
return Encoding.UTF8.GetBytes(responseBuilder.ToString());
}
当连接成功,你会发现客户端可以随意给服务器发送消息,但是服务器给客户端发送消息还是会断开连接这是因为报文的问题:
/// <summary>
/// 把发送给客户端消息打包处理
/// </summary>
/// <returns></returns>
/// <param name="message">Message.</param>
private byte[] SendMsg(string msg)
{
byte[] content = null;
byte[] temp = Encoding.UTF8.GetBytes(msg);
if (temp.Length < )
{
content = new byte[temp.Length + ];
content[] = 0x81;
content[] = (byte)temp.Length;
Buffer.BlockCopy(temp, , content, , temp.Length);
}
else if (temp.Length < 0xFFFF)
{
content = new byte[temp.Length + ];
content[] = 0x81;
content[] = ;
content[] = (byte)(temp.Length & 0xFF);
content[] = (byte)(temp.Length >> & 0xFF);
Buffer.BlockCopy(temp, , content, , temp.Length);
}
return content;
}
完成之后就可以畅游通讯了!!
再次声明参考文献:http://www.cnblogs.com/smark/archive/2012/11/26/2789812.html