我最近开始玩 HTML5 WebSockets,我有一个简单的 jQuery Web 客户端和一个控制台应用程序服务器。在阅读完握手后,这是我目前为客户准备的:
var socket = new WebSocket("ws://127.0.0.1:100", ["chat"]);
socket.onopen = function() {
console.log(socket.readyState);
}
这会将以下内容发送到我的服务器:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:100
Origin: http://localhost:57944
Sec-WebSocket-Protocol: chat
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: dBQ0epP7wmgHDEJc6Me95Q==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
现在,我的服务器代码。
首先,我阅读了上面从客户端发送的行,找到Sec-WebSocket-Key
值并将其保存到我的变量key
中。
然后我在此处附加维基百科文章中的幻数,即258EAFA5-E914-47DA-95CA-C5AB0DC85B11。这导致以下代码:
key = string.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
responseKey = Convert.ToBase64String(hash);
}
最后,我的响应密钥用于构造我发送回客户端的消息,即:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: u9guLPph1FeCPuOpFNs4F1b+UqY=
Sec-WebSocket-Protocol: chat
[blank line, as requested in spec]
但是,我socket.readyState
从 0 变为 3,然后失败并出现以下错误WebSocket connection to 'ws://127.0.0.1:100/' failed:
。
我已经读到这可能是由于我的服务器使用了与客户端不兼容的协议,但如果是这种情况,我不完全确定从哪里开始寻找。如果没有,有没有人知道如何解决这个问题或者我可以去哪里获取更多信息,因为我有点难过。
2013 年 3 月 21 日
在阅读了下面@djc 的评论后,我修改了我的服务器代码以发送回以下内容的确认:
using (StreamWriter sw = new StreamWriter(ns, Encoding.UTF8))
{
sw.NewLine = "\r\n\r\n";
// get response and calculate responseKey here (getting bytes as UTF-8 from client)
sw.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
sw.WriteLine("Upgrade: websocket");
sw.WriteLine("Connection: Upgrade");
sw.WriteLine("WebSocket-Origin: http://localhost:57944");
sw.WriteLine("WebSocket-Location: 127.0.0.1:100");
sw.WriteLine("Sec-WebSocket-Accept: " + responseKey);
sw.WriteLine("");
sw.Flush();
}
好吧,我不再在客户端上收到错误消息——但“socket.readyState”仍然为 0,并且我的socket.onopen
块从未被触发——尽管我看到客户端连接尝试通过。