【发布时间】:2016-04-19 02:44:05
【问题描述】:
我正在编写一个 c++ websocket 服务器,chrome 上的开发工具说 sec-websocket-accept 标头值不正确。我已经测试了几天,一切似乎都很好。客户端在没有调用 websocket onopen 的情况下以 readystate 3 关闭,尽管它在 chrome 开发工具中显示为 101。
这是我计算密钥的代码
string magickey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string key = msgkey.append(magickey);
unsigned char* sha_str = SHA1(reinterpret_cast<const unsigned char*>(key.c_str()), key.length(), nullptr);
string acceptkey = base64_encode(reinterpret_cast<const unsigned char*>(sha_str), strlen((char*)sha_str));
string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n";
handshake_response.append("Upgrade: websocket\r\n");
handshake_response.append("Connection: Upgrade\r\n");
handshake_response.append("Sec-WebSocket-Accept: "+acceptkey+"\r\n");
handshake_response.append("\r\n");
Chrome 响应
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 5T5MvxP1iz40vLpi3kQs/ifDaCo=
Chrome 请求
GET ws://localhost:4897/echo HTTP/1.1
Host: localhost:4897
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://localhost
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: LKF8lHGznbKGIgO1UzAOhg==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
它显示“WebSocket 握手期间出错:'Sec-WebSocket-Accept' 标头值不正确”。
Chrome 还显示了一个额外的帧接收大小为 79 字节的操作码 -1。
谢谢大家!
【问题讨论】:
-
acceptkey的值是多少? -
谢谢,我已经列出了问题中的关键值
-
您是否尝试过使用
\n而不是\r\n?此外,Chrome 输出中的行顺序似乎不同(来自您的代码)。 -
yes \n 完全一样,我还将 chrome 输出编辑为实际标题而不是解析。
-
我使用的是 Windows 8,所以 /r/n 应该是正确的。
标签: javascript c++ websocket