i am trying to make a web socket connection between a javascript client and a python server. I have managed to get the handshaking right, and i can send data from the javascript client, and decode it on the server.
The problem appears when i want to send data from the server. When i try to send clear ascii text i get this error on the client Websocket Error: [object Event]
. Naturally, so i want to "encode" the data before i send it. I have tried a lot of things, including basic base64. But nothing works. I stumbled upon this thread. Where it is an example of how to prepare data for sending.
Here is the code i've come up with so far:
def encodeFrame(bytesRaw):
bytesFormatted = []
bytesFormatted.append(129)
indexStartRawData = 0
if len(bytesRaw) <= 125:
bytesFormatted.append(len(bytesRaw))
indexStartRawData = 2
elif len(bytesRaw) >= 126 and len(bytesRaw) <= 65535:
bytesFormatted.append(126)
bytesFormatted.append(( len(bytesRaw) >> 8 ) + 255)
bytesFormatted.append(( len(bytesRaw) ) + 255)
indexStartRawData = 4
else:
bytesFormatted.append(127)
bytesFormatted.append(( len(bytesRaw) >> 56 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 48 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 40 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 32 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 24 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 16 ) + 255)
bytesFormatted.append(( len(bytesRaw) >> 8 ) + 255)
bytesFormatted.append(( len(bytesRaw) ) + 255)
indexStartRawData = 10
bytesFormatted.put(bytesRaw, indexStartRawData)
return bytesFormatted
I think most of it works right, but i have no idea what i should do with the last command: bytesFormatted.put(bytesRaw, indexStartRawData)
. I've tried just appending to the array, and using the buffer-format. But it won't work. The function which sends the data client.send(encodeFrame("test"))
in my case, only takes a buffer or string.
Does anyone have any idea how to do this "encoding"?