我试图从与python服务器通信的javascript客户端创建一个Websocket。
我的服务器是这样的:
connexions_asked, wlist, xlist = select.select([connexion_principal], [], [], 0.05)
for connexion in connexions_asked:
connexion_with_client, infos_connexion = connexion.accept()
clients_connected.append(connexion_avec_client)
initCo = clients_connected[-1].recv(1000)
initCo = initCo.decode()
initCo = initCo.split("\n")
secWebSocketKey = ""
for line in initCo:
if "Sec-WebSocket-Key" in line:
secWebSocketKey = line
break;
secWebSocketKey = secWebSocketKey.split("Sec-WebSocket-Key: ")[1]
magicStr = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
list_of_letters = list()
for letter in secWebSocketKey:
list_of_letters.append(letter)
list_of_letters.pop(-1)
for letter in magicStr:
list_of_letters.append(letter)
secWebSocketKey = "".join(list_of_letters)
secWebSocketKey = secWebSocketKey.encode()
sha1 = hashlib.sha1(secWebSocketKey).digest()
sha1 = base64.b64encode(sha1)
clients_connected[-1].send(b'HTTP/1.0 101 Switching Protocols\n')
clients_connected[-1].send(b'Content-Type: text/html\n')
clients_connected[-1].send(b'Connection: upgrade\n')
clients_connected[-1].send(b'Upgrade: websocket\n')
clients_connected[-1].send(b'Sec-WebSocket-Accept: ')
clients_connected[-1].send(sha1)
clients_connected[-1].send(b'\n')
clients_connected[-1].send(b'\n')
clients_connected[-1].send(b"<html><body><h1>Hello World</h1> this is my server!</body></html>")
我的js客户端是这样的:
var exampleSocket = new WebSocket("ws://localhost:12800");
exampleSocket.onopen = function (event) {
console.log("I'm connected");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
function sendMsg(str){
exampleSocket.send(str);
}
当我打电话给我的服务器时,一切似乎都有效,我可以找到&#34;我已连接&#34;在我的控制台上,但它引发了一个特殊的错误:
websocket.js:1 WebSocket连接到&#39; ws:// localhost:12800 /&#39;失败:一个或多个保留位开启:reserved1 = 0,reserved2 = 1,reserved3 = 1
我真的不知道它来自哪里。通过在互联网上搜索,我发现它可能来自对网络协议的过滤,但我不知道如何操纵它。
是否有人使用WebSockets出现此问题?