2013-12-21 98 views
2

我有我的蟒蛇服務器下面的代碼來創建併發送回響應握手爲什麼websocket握手失敗?

def HandShake(self, request): 
    specificationGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 
    websocketkey = "" 
    protocol = "" 
    for line in request.split("\n"): 
     if "Sec-WebSocket-Key:" in line: 
      websocketkey = line.split(" ")[1] 
     elif "Sec-WebSocket-Protocol" in line: 
      protocol = line.split(":")[1].strip() 

    print("websocketkey: " + websocketkey + "\n") 
    fullKey = hashlib.sha1(websocketkey.encode("utf-8") + specificationGUID.encode("utf-8")).digest() 
    acceptKey = base64.b64encode(fullKey) 
    print("acceptKey: " + str(acceptKey, "utf-8") + "\n") 
    if protocol != "": 
     handshake = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + str(acceptKey, "utf-8") + "\r\nSec-WebSocket-Protocol: " + protocol + "\r\n\r\n" 
    else: 
     handshake = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + str(acceptKey, "utf-8") + "\r\n\r\n" 
    print(handshake) 
    self.request.send(bytes(handshake, "utf-8")) 

我過我的計算與維基百科的例子中,關鍵的方法,所以我知道這是正確的。然而,每次當我嘗試連接到我的服務器,我得到以下錯誤:

Error during WebSocket handshake: Sec-WebSocket-Accept mismatch 

我不明白什麼即時做錯在這裏。有人看到發生了什麼問題嗎?

編輯:從打印輸出例如,打印在你的代碼的原始消息和製造握手

server started, waiting for connections... 
request: 
GET/HTTP/1.1 
Upgrade: websocket 
Connection: Upgrade 
Host: localhost:600 
Origin: http://localhost 
Pragma: no-cache 
Cache-Control: no-cache 
Sec-WebSocket-Key: yLffHPqMU4gIW2WnKq+4BQ== 
Sec-WebSocket-Version: 13 
Sec-WebSocket-Extensions: x-webkit-deflate-frame 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 


websocketkey: yLffHPqMU4gIW2WnKq+4BQ== 

acceptKey: A0eCd19URtkji0OPV162okWsCns= 

HTTP/1.1 101 Switching Protocols 
Upgrade: websocket 
Connection: Upgrade 
Sec-WebSocket-Accept: A0eCd19URtkji0OPV162okWsCns= 
+0

在您的問題中發佈'print()'調用的輸出。 –

+0

我編輯了op與打印輸出 – WillieWonka

回答

2

你有一個bug。

for line in request.split("\n"): 
    if "Sec-WebSocket-Key:" in line: 
     websocketkey = line.split(" ")[1] 

這就是在您的Sec-WebSocket-Key中返回"\r"

證據:

正常RFC行爲

Client Key: "yLffHPqMU4gIW2WnKq+4BQ==" 
Server Key: YVjKqlMRxlzzM70LScN9VoCsboI= 

不良行爲

Client Key: "yLffHPqMU4gIW2WnKq+4BQ==\r" 
Server Key: A0eCd19URtkji0OPV162okWsCns= 

鏈接AutobahnPython Sec-WebSocket-Key server side validation,和AutobahnPython hash calculation

+0

謝謝你解決它! – WillieWonka