2

我最近开始玩 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块从未被触发——尽管我看到客户端连接尝试通过。

4

1 回答 1

3

基于这个规范,我终于设法让它工作了。这是我的客户代码:

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!");
};

似乎需要包含websessioncookie 管理和['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();
}

现在我得到了一个有效的连接,但无法与服务器发送/接收数据——但我猜这是另一个故事。

于 2013-03-22T08:38:18.867 回答