Secure socket.io – websockets et al over SSL/TLS with tornadio2
I was surprised at how easy it was to enable SSL on socket.io with Tornado and Tornadio2 – read on!
We’ve been implementing some transport-layer security on PythonAnywhere, with HTTPS for our and our users’ web pages (due to go live in the next few days), but as some of you may know, normal HTTP(S) connections are only a part of PythonAnywhere.

For our in-browser console sessions, we use socket.io to carry user keystrokes and console output to and from our servers. And, until now, that traffic was all unencrypted. Well, no longer!
We have to give huge, huge props to MrJoes and the Tornadio team for their new project, tornadio2, which brings in compatibility with the latest improvements in socket.io and the websockets protocol. And massive thanks to the socket.io and Tornado teams too.
I decided to start by seeing whether I could adapt one of the standard tornadio examples to use SSL. This turned out to be an extraordinarily simple, 2-step process:
1 – amend socket.io on the client side to use https
2 – amend the tornado server side to use SSL.
Here’s the code:
Client-side – before:
conn = io.connect('http://' + window.location.host + '/', {
After:
conn = io.connect('https://' + window.location.host + '/', {
Server-side – before:
tornadio2.server.SocketServer(application)
After:
tornadio2.server.SocketServer(application, ssl_options={ "certfile": "server.crt", "keyfile": "server.key", })
That’s really not too bad is it?
All websockets connections are now secure, using the wss:// protocol. Here’s the Chrome Dev toolbar proving it!

XHR-polling, and JSON-polling sessions also use HTTPS.
I followed this guide to create self-signed ssl certificates for testing. And, you can see my example live on GitHub, where MrJoes has accepted my pull request! https://github.com/MrJoes/tornadio2/tree/master/examples/ssl_transports
By Allen, 3 October 2012 @ 7:54 pm
Hey, I’m a community blog curator for DZone. I wanted to talk with you about potentially featuring your blog on DZone’s content portals. Send me an email at allenc [at] dzone [dot] com and I’ll explain the details.