我有一个cpp服务器使用WinSock2和即时尝试连接到我的JavaScript客户端,这个服务器并没有工作,铬控制台说:“错误期间WebSocket握手:不正确'秒 - WebSocket - 接受'标题值“。 我比较我的sha1和base64函数与在线sha1和base64,所以问题不在这里。Websocket握手不起作用
Chrome的响应头:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-Websocket-Accept: NzdkYjg1Y2I4MDRlNTk0OGNmNzI1NzdjZDgwOTEwZWZiYWI1NzQ3Yw==
Chrome的请求头:
GET ws://localhost:8820/ HTTP/1.1
Host: localhost:8820
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4
Sec-WebSocket-Key: Y7a2ZKEz/VCM92Wya49iPA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
服务器代码:
//key is already defined.
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
key = sha1(key);
key = base64_encode(reinterpret_cast<const unsigned char*>(key.c_str()), key.length());
toClient = "HTTP/1.1 101 Switching Protocols\r\n";
toClient += "Upgrade: websocket\r\n";
toClient += "connection: Upgrade\r\n";
toClient += "Sec-Websocket-Accept: ";
toClient += key;
toClient += "\r\n\r\n";
sendData(sc, toClient);
客户端代码:
<!DOCTYPE HTML>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8820");
console.log("test");
ws.onopen = function()
{
alert("Connection.")
// Web Socket is connected, send data using send()
ws.send("20304user04user04user");
//alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Hey");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
您应该用wss而不是ws连接吗? – amiramw
我没有看到这样做的理由,我的代码应该工作,你有什么建议吗? – FlyingNades
您可以共享来自开发人员工具网络的握手的请求响应头吗? – amiramw