0

试图弄清楚我在这里做错了什么。我不断收到此错误“失败:WebSocket 握手期间出错:Sec-WebSocket-Accept 不匹配”。

以下是我从服务器得到的:

GET /?encoding=text HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8026
Origin: http://www.websocket.org
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: en04jzbfLcwcFhk5qnUxJg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36

我采取了“en04jzbfLcwcFhk5qnUxJg==”并添加“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”以获得以下信息:

en04jzbfLcwcFhk5qnUxJg==258EAFA5-E914-47DA-95CA-C5AB0DC85B11

所以我的回应是:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: MmJjMDQ2NTc0ZDE3MWVhNjA2ZmE0ZGNhYzQzYjliZmZkNzFmZDk1MQ==

我不确定我做错了什么,但从我在其他示例中看到的情况来看,我的 websocket 接受密钥似乎相当长。

以下是我的代码,任何想法都会有所帮助。

#!/usr/bin/env python

import socket
import thread
import hashlib
import base64
import binascii

def handshake(conn):
    request = conn.recv(1024).strip()
    print request

    specificationGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    websocketKey = ''

    lines = request.splitlines()
    for line in lines:
            args = line.partition(": ")
            if args[0] == 'Sec-WebSocket-Key':
                    websocketKey = args[2]
    print websocketKey

    fullKey = hashlib.sha1(websocketKey + specificationGUID).hexdigest()
    acceptKey = base64.b64encode(fullKey)

    response = 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ' + acceptKey + '\r\n\r\n'
    conn.send(response)
    print response

def accept(conn):
    def threaded():
        while True:
            handshake(conn)

thread.start_new_thread(threaded, ())

if __name__ == "__main__":
    HOST, PORT = 'localhost', 8026
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((HOST, PORT))
    server.listen(5)

    print "Listening on %s" % ("%s:%s" % server.getsockname())

    while 1:
            conn, addr = server.accept()
            accept(conn)
4

1 回答 1

1

我发现了问题,我使用了 .hexdigest() 而不是仅使用 .digest()。改变了,连接成功。

于 2013-08-15T23:06:23.663 回答