握手之后,我向服务器发送一些“你好”。在
#Chrome javascript console
~var s = new WebSocket('ws://127.0.0.1:8999');
s.onmessage = function(t){alert(t)};
s.onopen = function(){console.log('yes');}
~sock.send('Hello');
然后服务器尝试阅读此邮件并发回另一封邮件
^{pr2}$但是js控制台给我错误
WebSocket connection to 'ws://127.0.0.1:8999/' failed: Invalid frame header
更新
这里是我的服务器文件
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 9999))
sock.listen(5)
import hashlib
import base64
def makeHash(key):
hash0 = key.replace(" ","")+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
return hash0
handshaken = False
print("TCPServer Waiting for client on port 9999")
import sys
data = ''
header = ''
client, address = sock.accept()
while True:
if not handshaken:
data = client.recv(16).decode("utf-8");
header+=data
if header.find('\r\n\r\n')>=0:
key = header.split('Sec-WebSocket-Key: ')[1].split('\r\n')[0]
hash0 = makeHash(key).encode('utf-8')
hash1 = hashlib.sha1(hash0)
ready = base64.b64encode(hash1.digest())
newKey = str(ready)[2:][:-1]
answer = "HTTP/1.1 101 Switching Protocols\r\n"+"Upgrade: websocket\r\n"+"Connection: Upgrade\r\n"+"Sec-WebSocket-Accept: "+newKey+"\r\n\r\n"
client.send(answer.encode('utf-8'))
handshaken = True
else:
print("-")
else:
tmp = client.recv(1024)
data = str(tmp);
print(data)
answ = ('Hello').encode('utf-8')
client.send(answ)
目前没有回答
相关问题 更多 >
编程相关推荐