I'm trying to build a simple Python Websocket server. I managed to do the handshaking and all that stuff. However, I can't figure out how to decode the messages received from the browser, this is the raw output of what the server receives: 'xÙõKþ°pãüCY
. How am I supposed to decode that?

- 31
- 1
- 2
-
Did you implement the websocket protocol yourself or did you use one of the many existing libraries (which one)? Which of the many versions of the websocket protocol is actually in use between your browser and server? Can you include a minimal example? – Jean-Paul Calderone Dec 03 '11 at 15:07
-
I'm testing it with chrome, and it appears to be version 8. I'm not using any websocket library, just the 'default' socket library. – Ruben Sancho Dec 03 '11 at 15:11
-
Please have a look at this answer and it works perfectly http://stackoverflow.com/a/9778823/1193863 – naren Oct 08 '13 at 16:01
2 Answers
The WebSocket protocol involves a framing protocol. The browser does not just send raw application bytes to the server (nor vice versa). You need to parse the framing protocol to extract the raw bytes.
Many libraries have been implemented to do this parsing for you. You should probably try using one of those. One such library is http://pypi.python.org/pypi/txWS/0.6.1 but if you don't find that suitable, you can find others with a little searching.

- 47,755
- 6
- 94
- 122
What is the message you are sending from the client? And are you sure you are using Chrome 8 (that's 7 versions out of date). If you are in fact using a recent Chrome then your problem is likely that you have failed to unmask the payload. All client to server data in the newest versions of the protocol (the HyBi series) using a 4 byte running XOR mask to protect broken intermediaries from getting hijacked by malicious Javascript.
See section 5.3 of the spec for a description of the client to server payload masking.
Also, be aware that the payload data is UTF-8 encoded (in the older protocols too) and you can't just treat it as ASCII strings.
-
The message is a simple "Hello World!" and I meant the Websocket version is 8 (Browser sends this during handshake > Sec-WebSocket-Version: 8). As for unmasking the payload, does it work the same way in all versions? – Ruben Sancho Dec 03 '11 at 18:19
-
Then yes, you need to unmask the payload. The first four bytes of the payload are the mask. These need to be XOR'd with the following payload stream. The masking format has not change since it was introduced. – kanaka Dec 03 '11 at 18:42