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 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.

Details at:
This sample websocket implementation here just broadcasts messages from any connected client to all connected clients, like a group chat application.

To use this demo:
  • Download and pywebsock.html
  • Run "python". This starts the server on port 4545.
  • Open pywebsock.html with your browser.
  • Open pywebsock.html again. Well... to try the message broadcast feature, you would need at least one more browser tab/window with the same html file.
  • Type away to send messages from one window and see it appear on other windows.