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.


g said...

Thanks for the article. I have some problems however.
I can send longer data: I guess the problem is with line 48:
resp = bytearray([0b10000001, len(data)])

Could you please explain me what that line does and how to make this working for even really long messages?

g said...

I meant I >cannot< send long data...

Tanmay said...

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 :

g said...

Thanks for your help. I will look at the link, and try it own my own. :)

Ran said...

Thank you so much for the code. It solved my problem with getting and sending message. very simple and understandable. Cheers!

Bebop said...

You have no idea how you helpedme!! Sincerely, thank you