Skip to main content
 首页 » 编程设计

python之为什么 websocket 握手失败

2024年11月01日34me-sa

我有以下代码供我的 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")) 

我已经用维基百科上的例子测试了我计算 key 的方法,所以我知道这是正确的。然而,每次当我尝试连接到我的服务器时,我都会收到以下错误:

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= 

请您参考如下方法:

您的代码中有错误。

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 .