试图制作一个简单的文本聊天套接字服务器。我对编码服务器非常陌生。我有这个工作代码,但问题是 WebSocket() 默默地死在我身上:
javascript 控制台中的输出打开关闭
很少有资源可以帮助我理解这种行为。为什么我的 python 服务器在发送标头后会终止连接?我是否以正确的方式发送响应?任何帮助都将是惊人的。
Python代码:
import socketserver
import re
from base64 import b64encode
from hashlib import sha1
inited = 0
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
global inited
if(inited==0):
print(self)
text = self.request.recv(1024).strip()
self.upgradeConnection(text)
self.request.send("a sweet message from the server!".encode("utf-8"));
inited = 1
else:
self.request.sendall("second response!".encode("utf-8"));
def upgradeConnection(self,text):
#print("Client wants to upgrade:")
#print(text);
websocket_answer = (
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: {key}\r\n\r\n',
)
GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
#print(re.search(b'Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text))
key = (re.search(b'Sec-WebSocket-Key:\s+(.*?)[\n\r]+', text)
.groups()[0]
.strip())
#print(key.decode("utf-8"))
#print(key.decode("utf-8") + GUID)
#print(sha1((key.decode("utf-8") + GUID).encode("utf-8")))
response_key = b64encode(sha1((key.decode("utf-8") + GUID).encode("utf-8")).digest()).decode("utf-8")
#print(response_key)
response = '\r\n'.join(websocket_answer).format(key=response_key)
self.request.send(response.encode("utf-8"));
HOST, PORT = "localhost", 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
网页代码:
url = "ws://127.0.0.1:9999/";
var sk = new WebSocket(url);
sk.onopen = function(e){
console.log("open");
sk.send("the client is here!!");
}
sk.onmessage = function(e){
console.log("message");
console.log(e.data);
}
sk.onerror = function(e){
console.log("error");
}
sk.onclose = function(e){
console.log("closed");
}