Apr. 29th, 2012

<!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);

Below are index.html and server.js sources. The server expects the index.html file as well as SSL key.pem and cert.pem to be located in the current directory.

<!doctype html>
<meta charset="utf-8">
<title></title>

<script>
var socket = new WebSocket("ws://localhost/");

socket.onmessage = function(msg) {
	eval(msg.data);
};
</script>

var read = require("fs").readFileSync;

function server(socket)
{
	socket.on("message", function(msg) {
		socket.send("alert(\"" + msg + "\");");
	});
	socket.send("socket.send(\"Hello World!\");");
}

function client(ws)
{
	var html = read("index.html", "utf8");

	return function(request, response) {
		response.writeHead(200, {
			"Content-Type": "text/html"
		});
		response.end(html.replace("ws", ws));
	};
}

function uniweb(host, ws, port)
{
	(new (require("ws").Server)({
		server: host
	})).on("connection", server);
	host.on("request", client(ws));
	host.listen(port);
}

uniweb(require("http").createServer(), "ws", 80);
uniweb(require("https").createServer({
	key: read("key.pem"),
	cert: read("cert.pem")
}), "wss", 443);

Profile

Anton Salikhmetov

November 2018

S M T W T F S
    123
45678 910
11121314151617
18192021222324
252627282930 

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 10th, 2025 03:49 pm
Powered by Dreamwidth Studios