2017-05-30 126 views
0

我有一個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> 

+0

您應該用wss而不是ws連接嗎? – amiramw

+0

我沒有看到這樣做的理由,我的代碼應該工作,你有什麼建議嗎? – FlyingNades

+1

您可以共享來自開發人員工具網絡的握手的請求響應頭嗎? – amiramw

回答

2

我手動試圖建立響應:

  1. 原始SHA1摘要的級聯的字節是77db85cb804e5948cf72577cd80910efbab5747c
  2. 字節立足64:d9uFy4BOWUjPcld82AkQ77q1dHw=

這比你有什麼不同。您正在將這些字節的十六進制字符串表示形式轉換爲基數64,而不是原始字節到基數64.

+0

所以我用[this](http:// renenyffenegger .ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp)方法,對我來說似乎很好,我想我真的沒有遇到這個問題 – FlyingNades

+0

@FlyingNades base64編碼不是問題。你的sha1功能是。在類似的問題上檢查[我的回答](https://stackoverflow.com/a/35989898)。這可能會讓你的問題更清楚。 –

+0

@gre_gor所以sha1或base64函數都不是問題,我發送給base64函數的sha1表示是問題,對嗎? – FlyingNades