HTML5 WebSocket Server - Work in Progress
So, I thought I'd devise a websocket server in Python. I've been tweeting some stuff about that too, but as soon as I wanted to publish the source code, I accidentally deleted websocket.py, instead of websocket.pyc (which I didn't want to occur on github). That was quite dumb...
A basis for further development
Today I started rewriting it from scratch. Unfortunately, the "draft76" implementation I wrote back then is already outdated. So the code isn't really all that useful, except that I got a basic version working, though it still blocks threads that have a client connected, and the server won't shutdown until the clients disconnect. That is a design error and a major bug that demands yet another rewrite.
Anyway, the part that cost me the most time was figuring out the opening handshake code, so here it is:
#!python def _challenge_response(self, key1, key2, key3): """The response to a WebSocket challenge. - key1 is the contents of the Sec-WebSocket-Key1 header - key1 is the contents of the Sec-WebSocket-Key2 header - key3 is the contents of the 8 bytes long request body""" def extract_number(key): number = '' spaces = 0 for ch in key: if ch == " ": spaces += 1 elif ch.isdigit(): number += ch number = int(number) if spaces > 0 and number > 0 and number % spaces == 0: return int(int(number) / spaces) raise ValueError("Invalid challenge part %s, can not extract number" % key) self._debug("Challenge: \n\t%s\n\t%s\n\t%s" % (key1, key2, key3)) packed = pack('>L', extract_number(key1)) packed += pack('>L', extract_number(key2)) packed += key3 response = hashlib.md5(packed).digest() self._debug("Response: %s" % response) return response
Current development code
Just to be sure I won't delete the source code again, I just published the development code on my github.
< Return to main page