Always an Error on the First Message
Currently I'm working on setting up a basic WebSockets script. I can get the client to connect to the server, but whenever the server sends the first message to the client the client registers and error, and from what I can tell the readyState is open, and should allow the message to come through. The message has the correct beginning of /x00 and /xff. I can't figure out what's wrong.
EDIT: Here are the codes that seem to be causing whatever the error is. data.js just holds what the Python server used to set up the server so I only have to change one file when I test it out and the port hasn't timed out yet.
Client-side:
<html>
<head>
<script type="text/javascript" src="data.js">
</script>
<script type="text/javascript">
var ws, error
init = function() {
ws = new WebSocket("ws://127.0.0.1:"+port+"/websockets/main.py")
ws.onopen = function() {
console.log("Connected")
log("Connected")
}
ws.onmessage = function(e) {
console.log("Received data")
log(e.data)
}
ws.onerror = function(e) {
console.log(e)
ws.send("Error occurred. Resend")
}
}
log = function(msg) {
document.getElementById("log").appendChild(document.createElement("br"))
document.getElementById("log").innerHTML = document.getElementById("log").innerHTML+msg
}
</script>
</head>
<body onload="init()">
<div id="log">
</div>
</body>
</html>
Server-side:
import threading, hashlib, socket, time, re, struct
class WebSocketThread(threading.Thread):
def __init__(self, channel, details, websocket):
self.channel = channel
self.details = details
self.websocket = websocket
threading.Thread.__init__(self)
def run(self):
print("> Received connection ", self.details[0])
self.handshake(self.channel)
while True:
self.interact(self.channel)
def finduser(self, client):
for user in self.websocket.users:
if user.socket == client:
return user
return 0
def send_data(self, user, data):
user.socket.send(self.wrap(data))
print ("> Sent data", data, "to", user)
def recv_data(self, client, count):
data = client.recv(count)
return data
d开发者_JAVA技巧ef handshake(self, client):
shake = self.recv_data(client, 256)
our_handshake = self.create_response(shake)
client.send(our_handshake)
print ("> Accepted client ", self.finduser(client))
self.send_data(self.finduser(client), "Test")
def interact(self, client):
users = self.websocket.users
this_user = self.finduser(client)
data = self.unwrap(self.recv_data(client, 256))
print ("> Received data ", data, "from", this_user)
def create_response(self, data):
key3 = ""
lines = data.splitlines()
resource = re.compile("GET (.*) HTTP").findall(data)
resource = resource[0]
for line in lines:
parts = line.partition(": ")
if parts[0] == "Host":
host = parts[2]
elif parts[0] == "Origin":
origin = parts[2]
elif parts[0] == "Sec-WebSocket-Key1":
key1 = parts[2]
elif parts[0] == "Sec-WebSocket-Key2":
key2 = parts[2]
key3 = line
spaces1 = key1.count(" ")
spaces2 = key2.count(" ")
num1 = int("".join([c for c in key1 if c.isdigit()]))/spaces1
num2 = int("".join([c for c in key2 if c.isdigit()]))/spaces2
token = hashlib.md5(struct.pack(">II8s", num1, num2, key3)).digest()
return "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: %s\r\nSec-WebSocket-Location: ws://%s%s\r\nSec-WebSocket-Protocol: sample\r\n\r\n%s\r\n"% (origin, host, resource, token)
def unwrap(self, data):
return data[1:-1]
def wrap(self, data):
return ("\x00"+data+"\xff")
Try to remove last \r\n after your token:
return "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: %s\r\nSec-WebSocket-Location: ws://%s%s\r\nSec-WebSocket-Protocol: sample\r\n\r\n%s"% (origin, host, resource, token)
I'm sure it will solve your problem :)
精彩评论