Python, CherryPy and Websockets – hosted

To set up websockets on a host can take a few extra steps. The host needs to know what to do with the websocket traffic.

It took a few attempts to get a Python/websockets sample up and running. The first websocket library I used (for Python/Bottle) worked very well on my local machine, but the host didn’t have the required libraries installed and didn’t give me enough access rights to fix this. I switched to a different framework and library, which worked much better.

  1. Create a new (WebFaction) application, wstest, custom websocket
    1. Save it, attach it to a domain/website, and make a note of the port
  2. ssh into the host
  3. Set up the requirements:
    1. pip install cherrypy
    2. pip install ws4py
    3. pip install argparse
  4. Switch to the application’s folder (cd webapps/wstest)
  5. Create index.html and site.py as created by Sylvain Hellegouarch, but with following changes:
    ….
    return index_page {d34bf16ac7b745ad0d2811187511ec8954163ba9b5dbe9639d7e21cc4b3adbdb} {‘username’: “User{d34bf16ac7b745ad0d2811187511ec8954163ba9b5dbe9639d7e21cc4b3adbdb}d” {d34bf16ac7b745ad0d2811187511ec8954163ba9b5dbe9639d7e21cc4b3adbdb} random.randint(50, 1000),
    ‘ws_addr’: ‘ws://<url>/ws’}
    ….
    cherrypy.config.update({
    ‘server.socket_host’: ‘127.0.0.1’,
    ‘server.socket_port’: <the application’s port – see above>
    })

    1. Important (this took me a while to figure out): the original websocket url (first/second line, above) in the sample code is “ws://localhost:9000/ws”. Having tried a bunch of different ports (80, 9000, the application’s port, etc), the correct solution is to leave the port off completely, so just use “ws://<url>/ws” instead
  6. Start CherryPy: python2.7 site.py
    1. Since you’re running this still attached to your terminal session, when you close the (ssh) terminal the process will stop as well.
  7. Now open the url in two separate browsers. You should be able to enter messages in either browser and see it appearing in both