Some of the readers may have noticed that I was using plain WebSockets ('ws://' URLs). It's recommended to use Secure WebSockets instead ('wss://' URLs), so I thought of playing with the 'ws' node.js module and "add TLS".
On github there's an example in this direction (see below), but I must admit I didn't understand some implications at first.
I thought the instantiation of an HTTPS server was just coincidental and meant to provide the web pages and scripts in the example, and that the configuration of 'ws' with 'ssl: true' and certificates was independent.
It turns out it's not. The best description of my understanding is that you need an HTTPS server to "decorate" the WebSocket module. The HTTPS server will take care of connection instantiation and encryption, while the WebSocket module, "listening" on the same port, will take over when the Upgrade request [1] from the client is received.
Here's a snippet of the solution I've adopted, based on the example above:
You can see that the version for plain WebSocket (commented out) had the configuration object passed to the WebSocket constructor (well, in fact, you just need to pass '{ port: 8080 }'), while the secure solution passes the entire HTTPS server object to the WebSocket constructor.
Something similar (using express) has been described in this post.
Note, if you're using self-signed certificates, that you should first access the site and accept the security exception, or the client won't be happy.
An useful tool to debug WebSockets comes as Chrome extension: Simple WebSocket Client.
[1] The Upgrade request looks like this (from RFC 6455);
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13