我正在尝试握手,但我不断收到错误: 失败:WebSocket握手期间出错:错误' Sec-WebSocket-Accept'标题值
我做错了什么?
服务器:
<!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>
客户端:
{{1}}
答案 0 :(得分:0)
这对我有用:
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'))