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.
- Create a new (WebFaction) application, wstest, custom websocket
- Save it, attach it to a domain/website, and make a note of the port
- ssh into the host
- Set up the requirements:
- pip install cherrypy
- pip install ws4py
- pip install argparse
- Switch to the application’s folder (cd webapps/wstest)
- 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>
})- 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
- Start CherryPy: python2.7 site.py
- Since you’re running this still attached to your terminal session, when you close the (ssh) terminal the process will stop as well.
- Now open the url in two separate browsers. You should be able to enter messages in either browser and see it appearing in both