Monday, March 11, 2013

Minimal WebSocket Broadcast Server in Python

There are many websocket server implementations. Any serious attempts at building in websockets into the application should look at libraries like http://libwebsockets.org/ or wrappers on such. But a small lightweight implementation of your own, specific to your applications is good and fun. Here's a very simplistic one I made, while reading through the rather simple websocket protocol.

The websocket connection starts as a regular HTTP connection from the client, with certain headers that indicate that the client is requesting a websocket connection. The server responds with specific response headers if it accepts the connection. Subsequent messages flow in either direction. Messages are framed with a few bytes of header data that can contain the type of data, data length and a basic XOR mask. Longer messages are broken up into multiple frames.

Glad that you are finding this code snippet useful. As I mentioned in the article, this snippet is a very simple but incomplete implementation. You are right in identifying where the limitation comes from.

To send larger amounts of data you need to implement extended payload length as mentioned in section 5.2 of the rfc : http://tools.ietf.org/html/rfc6455#section-5.2