阻止WebSocket请求添加默认标头

时间:2019-10-29 20:16:55

标签: python python-3.x websocket

我正在编写一个websocket客户端以连接到我没有源代码的服务器(黑匣子测试)。

当我尝试使用以下代码连接到服务器时,默认标头不断添加到请求中,结果由于RFC 6455的规范而仅允许单个{{1} }用于标题。

Sec-WebSocket-Key

但是,此请求将被发送:

socket_key = "Sec-WebSocket-Key: " + r.headers['Sec-WebSocket-Accept']

websocket.enableTrace(True)
ws = create_connection('wss://example.com/socket.io/?EIO=3&transport=websocket', headers=[socket_key])

如何防止第一个--- request header --- GET /socket.io/?EIO=3&transport=websocket HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: example.com Origin: http://example.com Sec-WebSocket-Key: <Generated WebSocket Key> Sec-WebSocket-Version: 13 Sec-WebSocket-Key: <socket_key from above> 头出现,或用我自己的WebSocket密钥替换其在请求中生成的WebSocket密钥?

1 个答案:

答案 0 :(得分:1)

header参数传递字典而不是列表:

my_header = { "Sec-WebSocket-Key" : "12345abcde" }
ws = websocket.create_connection("ws://127.0.0.1:8000/", header = my_header)

对于此代码,我看到以下出站请求:

websocket:--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8000
Origin: http://127.0.0.1:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 12345abcde