Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active August 29, 2015 14:16
Show Gist options
  • Save bellbind/a868caf9628b4636c952 to your computer and use it in GitHub Desktop.
Save bellbind/a868caf9628b4636c952 to your computer and use it in GitHub Desktop.
[websocket][iojs]Basic Usage of raw W3C WebSocket API (with iojs server)
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Raw WebSocket API</title>
<script src="script.js"></script>
</head>
<body>
<div>
[<input id="name" type="text" value="anon" style="width: 100px" />]
<input id="message" type="text" style="width: 300px" />
<button id="send">send</button>
</div>
<div>
<ul id="log" style="overflow: auto; width: 500px; height: 400px"></ul>
</div>
<div>
<a href="https://gist.github.com/bellbind/a868caf9628b4636c952">source codes</a>
</div>
</body>
</html>
{
"name": "websocket-basics",
"version": "0.0.1",
"description": "websocket server and client basic codes",
"dependencies": {
"faye-websocket": "*",
"mime-types": "*"
},
"scripts": {
"start": "iojs ws-server.js"
},
"engines": {
"iojs": "1.4.x"
}
}
web: npm start
;window.addEventListener("load", function () {
"use strict";
var name = document.getElementById("name");
var message = document.getElementById("message");
var log = document.getElementById("log");
var send = document.getElementById("send");
var wsurl = location.origin.replace(/^http/, "ws") + "/bs/";
var socket = null;
var sender = function (ev) {
console.log("[send]");
socket.send("[" + name.value + "] " + message.value);
};
(function openSocket() {
socket = new WebSocket(wsurl);
socket.addEventListener("open", function (ev) {
console.log("[open]");
send.addEventListener("click", sender, false);
}, false);
socket.addEventListener("message", function (ev) {
console.log("[message] " + ev.data);
var li = document.createElement("li");
li.textContent = ev.data;
log.insertBefore(li, log.firstChild);
}, false);
socket.addEventListener("close", function (ev) {
console.log("[close]");
send.removeEventListener("click", sender, false);
requestAnimationFrame(openSocket); // reconnect
}, false);
})();
}, false);
// Simple Broadcast WebSocket server
// $ npm install faya-websocket mime-types
// $ iojs ws-server.js
var http = require("http");
var fs = require("fs");
var path = require("path");
// 3rd party libs
var WebSocket = require("faye-websocket"); // W3C API compliant interface
var mime = require("mime-types");
var fileServer = function (req, res) {
console.log("[file server]", req.method, req.url);
if (req.method !== "GET") {
res.writeHead(405, {allow: "GET"});
return res.end();
}
var loc = req.url.endsWith("/") ? req.url + "index.html" : req.url;
var file = path.join(__dirname, loc);
fs.createReadStream(file).once("readable", function () {
console.log("[exist]", file);
var mtype = mime.lookup(loc) || "application/octet-stream";
var charset = mime.charset(mtype);
var ctype = mtype + (charset ? "; charset=" + charset : "");
res.writeHead(200, {"content-type": ctype});
this.pipe(res);
}).once("error", function (er) {
console.log("[not exist]", file);
res.writeHead(404);
res.end();
});
};
// single broadcast hub
var BroadcastServer = function () {
this.sockets = new Map();
};
BroadcastServer.prototype.onUpgrade = function (req, socket, head) {
console.log("[upgrade]", req.method, req.url);
var sockets = this.sockets;
var ws = new WebSocket(req, socket, head);
ws.addEventListener("open", function (ev) {
console.log("[open]", ws.url);
sockets.set(ws, {});
}, false);
ws.addEventListener("message", function (ev) {
console.log("[message]", ev.data);
for (var socket of sockets.keys()) {
socket.send(ev.data);
}
}, false);
ws.addEventListener("close", function (ev) {
console.log("[close]", ws.url);
sockets.delete(ws);
}, false);
};
var bs = new BroadcastServer();
var server = http.createServer(fileServer);
server.on("upgrade", bs.onUpgrade.bind(bs));
server.listen(process.env.PORT || 8080);
console.log("open http://localhost:8080/");
@bellbind
Copy link
Author

bellbind commented Mar 5, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment