为什么websocket握手失败?

时间:2013-12-21 20:43:40

标签: python websocket

我有以下代码供我的python服务器创建并将响应发送回握手

    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=

1 个答案:

答案 0 :(得分:2)

您的代码中存在错误。

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 validationAutobahnPython hash calculation的链接。