Reputation: 9458
I'm having some issues decoding data sent over websockets from Chrome (JavaScript) to a python server (using low-level socket apis). I've handled the handshake properly, the readyState
of the websocket is OPEN when I use .send(...)
. I receive byte data (per the specs), but no matter how I try to decode it, it comes out as jibberish or triggers an exception.
javascript
var we = new WebSocket(url);
we.send("string data");
python
data = socket.recv(1024) # socket from sock.accept(...)
#handle data
I've tried data.decode('utf-8')
as that seems like it would be the obvious solution (throws an error). I've tried stripping \x80
and \x81
(I think - I read it somewhere on StackOverflow), but it still throws an error...
I've tried base64 decoding - which I found in an answer here on SO (but that doesn't make sense so...)
Anything I'm missing?
Upvotes: 1
Views: 654
Reputation: 19564
I'm not versed in WebSocket communication, but according to this answer, the data is encoded (see the part on Receiving Messages)
>>> pkt = [int(x, 16) for x in '81:85:86:56:99:b4:ee:33:f5:d8:e9'.split(':')]
>>> pkt[0] # header should be 129 for text mode
129
>>> len = pkt[1] & 0b01111111
>>> len
5
>>> mask = pkt[2:6]
>>> data = pkt[6:]
>>> for i,c in enumerate(data):
... print chr(c ^ mask[i % 4])
...
h
e
l
l
o
Note, this is just an example of decoding your specific example data and does not take the full spec into account. For instance, the data length can be multiple bytes (so the position of the mask and data block may vary).
Upvotes: 2