Combined HTTP/HTTPS/WebSocket Server
Apr. 29th, 2012 11:15 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
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);