Getting started web sockets using pywebsocket, mod_python and apache in Ubuntu

Since my initial posts on websockets I’ve moved to pywebsocket, this is a python based project which provides a websocket extension to apache via mod_python. It can also run a standalone web server/websocket server if required.

I made the move from node.js based systems as I was more comfortable developing using python and apache (even though I don’t know much python) and also most of the other systems I wish to integrate work well with python. I also feel that using a python extension to apache is a more sensible solution which is able to work on most webservers without major reconfiguration.


The install process for apache, mod_python and pywebsocket is quite trivial, I followed instructions written by Travis Glines, care should taken to make sure you use the correct apache config files, I didn’t and as a result spent ages wondering why it didn’t work!

A websocket compatible browser is also required (i.e. daily build of Firefox 4, Chrome/Chromium v 6.0.414+) earlier versions of chrome can be used however they use an older handshake protocol not enabled in pywebsocket by default, if you wish to use an older browser the you need to add:

[sourcecode language=”bash”]PythonOption mod_pywebsocket.allow_draft75 On[/sourcecode]

to the appropriate apache conf file (the same one you added all the other stuff to!).


pywebsocket comes with an example in /src/example however these are aimed at the standalone mode, however the supplied handler can be used to test the apache version.

  1. Place in the websocket handler folder defined during installation.
  2. Check it has permission to be executed
  3. Use the following html/JS to connect to your new handler, it will connect then on clicking the window will send a message with string "Click!" down the websocket and display anything returned, in this case the sent message is echoed so you should see "Click!" appended to #msg on every click:
    <!DOCTYPE html>
    <script src=''></script>
        $(document).ready(function() {
    			function debug(str) {
    			ws = new WebSocket('ws://localhost/echo');
    /* Define websocket handlers */
          ws.onmessage = function(evt) {
          ws.onclose = function() {
    				debug('socket closed');
          ws.onopen = function() {
    /* Define click handler */
    	$(document).click(function () {
    	<div id='debug'></div>
    	<div id='msg'></div>

Once that’s working you can go on to write your own handlers with the filenames being suffixed with eg: ws://localhost/foo will point to

Moving On

I’ve already got a few ideas in mind for what I’d like to implement using web sockets although at the moment debugging files is proving very tricky as there is no simple debugging available and I’m working blind with a minimal knowledge of python!