gpt4 book ai didi

python web 套接字握手不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:37 25 4
gpt4 key购买 nike

我正在尝试握手,但我不断收到错误:失败:WebSocket 握手期间出错:“Sec-WebSocket-Accept” header 值不正确

我做错了什么?

服务器:

import socket
import re
from base64 import b64encode
from hashlib import sha1
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
websocket_answer = (
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: {key}\r\n\r\n',
)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host='10.10.10.12'
port=8999
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
client_list = []

while True:
data = conn.recv(1024)
if not data:
break
if(s not in client_list):
client_list.append(s)
key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', data.decode('utf-8'))
.groups()[0]
.strip())
print('key' + key)
response_key = b64encode(sha1((key + GUID).encode('utf-8')).hexdigest().encode('utf-8')).decode('utf-8')
response = '\r\n'.join(websocket_answer).format(key=response_key)
print('_________________RESPONSE________________')
print(response.encode('ascii'))
conn.send(response.encode('utf-8'))
else:
print(str(data))
print(data.decode('utf-8'))

客户:

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
var s = new WebSocket('ws://10.10.10.12:8999');
s.onmessage = function(t){console.log(t)};
s.onopen = function(){
s.send('hello from client');
}
</script>
</head>
<body>
</body>
</html>

https://docs.python.org/2/library/socketserver.html

最佳答案

这对我有用:

import socket
import re
from base64 import b64encode
from hashlib import sha1
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
websocket_answer = (
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: {key}\r\n\r\n',
)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host='10.10.10.12'
port=8999
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()
#print('Connected by', addr)
client_list = []

while True:
data = conn.recv(1024)
if not data:
break
if(s not in client_list):
client_list.append(s)
key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', data.decode('utf-8'))
.groups()[0]
.strip())
#print('key' + key)
sha1f = sha1()
sha1f.update(key.encode('utf-8') + GUID.encode('utf-8'))
response_key = b64encode(sha1f.digest()).decode('utf-8')
response = '\r\n'.join(websocket_answer).format(key=response_key)
#print('_________________RESPONSE________________')
#print(response)
conn.send(response.encode('utf-8'))
else:
pass
#print(data.decode('utf-8'))
print(str(data).encode('utf-8').decode('utf-8'))

关于python web 套接字握手不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com