Websocket握手-WebSocket握手期间错误:错误的“ Sec-WebSocket-Accept”头值

时间:2020-09-15 11:37:29

标签: python sockets http websocket

我正在使用Python的 socket 来响应 Websocket 请求,而我遇到Sec-WebSocket-Accept标头的问题。以前可能会遇到这样的问题,但没人为我工作

https://developer.mozilla.org上的文档指出要建立连接:

服务器采用握手请求中发送的 Sec-WebSocket-Key 的值,附加258EAFA5-E914-47DA-95CA-C5AB0DC85B11,采用 SHA-1 值,然后进行 base64 编码。

我当前发送的响应包含在一个函数中,该函数从请求中获取密钥 并按照文档中的内容进行操作

def socket101(self,template,key):
    key = key.strip()
    key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" #Add the key
    key = sha1(key.encode()).digest() #Take the sha1
    key = b64encode(key) #B64 encode it
    return (b"HTTP/1.1 101 Switching Protocols\n"
            +b"Content-Type: text/html\n"
            +b"Connection: Upgrade\n"
            +b"Upgrade: websocket\n"
            +"Sec-WebSocket-Accept: {}\n".format(key).encode()
            +b"\n"
            )    

然后我按如下方式调用上述方法

def AwaitMessage(client,address):
    while True:
        data = client.recv(1024)
        try:
            if str(data.strip()) != '': 
                headers = ParseHeaders(data) #Parses the request headers
                HTTP_MSG = socket101(headers['Sec-WebSocket-Key']) #Call the function above passing the key
                client.send(HTTP_MSG) #Send the message
        except Exception as f:
              pass
    client.close()

但这不希望我做什么,并且会引发以下错误:

WebSocket握手过程中的错误:错误的'Sec-WebSocket-Accept'标头值

浏览器未提供任何有关为什么它不正确且我猜不到的信息。

JavaScript 代码只是与套接字建立连接。

const host = window.location.host
const PORT = 8000;
const socket = new WebSocket(`ws://${host}:${PORT}/ws/connection`)

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下代码对我有用

        "Poly"

我几乎可以确定它与我上面的东西完全相同,但是上面的东西不起作用

相关问题