Minimal Universal Secure Web Client
Apr. 29th, 2012 03:37 am<!doctype html> <meta charset="utf-8"> <title></title> <script> var socket = new WebSocket("wss://127.0.0.1:8888/"); socket.onmessage = function(msg) { eval(msg.data); }; </script>
The above HTML5 code successfully validated by W3C, unlike the previous one, uses the secure WebSocket protocol. One can easily create a Node.js-based secure WebSocket server for such a client as follows. We assume files named key.pem
and cert.pem
to contain the private key and the corresponding certificate both PEM-formatted, and that server.js
contains the source code from below. If you have the ws
package installed using npm install ws
, running node server.js
will then start the server.
var fs = require("fs"); var https = require("https"); var ws = require("ws"); var host = { server: https.createServer({ key: fs.readFileSync("key.pem"), cert: fs.readFileSync("cert.pem") }) }; (new ws.Server(host)).on("connection", function(socket) { socket.on("message", function(msg) { socket.send("window.alert(\"" + msg + "\");"); }); socket.send("socket.send(\"Hello World!\");"); }); host.server.listen(8888);