我最近开始使用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
。
然后我从Wikipedia article here追加幻数, 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
块永远不会被触发 - 尽管我看到客户端连接尝试通过。
答案 0 :(得分:3)
基于this specification我终于成功了。这是我的客户代码:
var socket = new WebSocket("ws://localhost:8181/websession", ['chat','superchat']);
socket.onopen = function()
{
$("div#messages").append("<p class=\"event\">Socket is connected.</p>");
socket.send("Thanks!");
};
似乎包含websession
用于Cookie管理,并且需要['chat','superchat']
协议。
服务器:
using (TcpClient client = listener.AcceptTcpClient())
using (NetworkStream stream = client.GetStream())
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
using (StreamWriter sw = new StreamWriter(stream, Encoding.UTF8))
{
Dictionary<string, string> headers = new Dictionary<string, string>();
string line = string.Empty;
while ((line = sr.ReadLine()) != string.Empty)
{
string[] tokens = line.Split(new char[] { ':' }, 2);
if (!string.IsNullOrWhiteSpace(line) && tokens.Length > 1)
{
headers[tokens[0]] = tokens[1].Trim();
}
}
string responseKey = "";
string key = string.Concat(headers["Sec-WebSocket-Key"], "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
responseKey = Convert.ToBase64String(hash);
}
sw.WriteLine("HTTP/1.1 101 Switching Protocols");
sw.WriteLine("Upgrade: websocket");
sw.WriteLine("Connection: Upgrade");
sw.WriteLine("Sec-WebSocket-Accept: " + responseKey);
sw.WriteLine("Sec-WebSocket-Protocol: chat");
sw.WriteLine("");
sw.Flush();
}
现在我得到了一个有效的连接,但无法通过服务器发送/接收数据 - 但这是我想的另一个故事。