Skip to content

Commit

Permalink
-
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeHitchens committed Jun 13, 2011
1 parent b41013b commit d9fde60
Show file tree
Hide file tree
Showing 3 changed files with 176 additions and 81 deletions.
79 changes: 68 additions & 11 deletions docroot/index.html
@@ -1,24 +1,81 @@
<html>
<head>
<style> body { padding: 3em; } </style>
<script src=jquery.js></script>
</head>
<body>
<h1>node-jsond test page</h1>

Send: <input onchange="changed(this.value)"><p>
Rcvd: <textarea id=rcvd></textarea><p>

<script src=jsonc.js></script>

<h1>Test Page</h1>

<b>Enter message values here</b><br>
Construct a message by entering the key/value pairs in this box, one per line.
<textarea id=vals cols=80 rows=8>
m hello!
</textarea>
<input id=sendbtn type=button value="Send"><p>

<b>This is the message actually sent to server</b><br>
<textarea id=msgsent cols=80 rows=8></textarea> <p>

<b>This is the response message from the server</b><br>
<textarea id=msgrcvd cols=80 rows=8></textarea><p>



<script>

var rcvd = document.getElementById("rcvd")

jsond.opts({port: 30304})
apiURL = "http://localhost:50505/api/"

function el(id) { return document.getElementById(id) }
function o2j(o) { return JSON.stringify(o) }
function j2o(j) { return JSON.parse(j) }


function jsondReady() {

function changed(v) {
var msg = {m:v}
jsond.send(msg, function(response) {
rcvd.value = "Response: "+JSON.stringify(response);

var vals = el("vals")
var msgrcvd = el("msgrcvd")
var msgsent = el("msgsent")
var seq = 1;

$("#sendbtn").click(function() {
var lines = vals.value.split("\n"),
msg = {},
line, i, m

msgrcvd.value = ""
msgsent.value = ""

for(i = 0; i < lines.length; i++) {
line = lines[i]
m = line.match(/^([^\s]+) (.*)$/)
if(m) {
msg[m[1]] = m[2]
}
}
msgsent.value = o2j(msg)

jsond.send(msg, function(rmsg) {
msgrcvd.value = o2j(rmsg)
})
})

}


function docReady() {
var d = document, e = d.createElement('script')
e.id = "jsond"
e.async = false
e.src = apiURL
e.onload = jsondReady
d.body.appendChild(e)
}

$(document).ready(docReady)

</script>

163 changes: 101 additions & 62 deletions jsond.js
Expand Up @@ -22,108 +22,147 @@ IN THE SOFTWARE.
*/

// ==================================================
// json daemon (server code)
// ==================================================

var fs = require("fs"),
url = require("url"),
util = require("util"),
http = require("http")
http = require("http"),
l = console.log

function j2o(j) { try { return JSON.parse(j) } catch(e) { return null } }
function o2j(o) { return JSON.stringify(o) }


var j2o = function(j) { try { return JSON.parse(j) } catch(e) { return null } }
var o2j = function(o) { return JSON.stringify(o) }


var fail = function(res, err) {
var msg = o2j({error:err.message})
function r500(res, s) {
if(!s)
s = "ERROR"
res.writeHead(500, {
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
"Content-Length": msg.length,
"Content-Length": s.length,
})
res.end(msg)
res.end(s)
}


var isReadableFile = function(path) {
try {
if(fs.statSync(path).isFile()) {
fs.close(fs.openSync(path, "r"))
return true;
}
}
catch(e) { }
return false
}

function r404(res) {
var msg = "FILE NOT FOUND"
res.writeHead(404, {

function finish(res, s) {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
"Content-Length": msg.length,
"Content-Length": s.length,
})
res.end(msg)
res.end(s)
}


var post = function(req, res, msgHandler) {
var jsonIn = ""
var readBody = function(req, res, cb) {
var body = ""

req.setEncoding("utf8")
req.on("data", function(d) {
jsonIn += d
body += d
})
req.on("error", function(e) {
fail(res, e)
r500(res, "error reading input")
})
req.on("end", function() {
var objIn = j2o(jsonIn)
if(!objIn) {
fail(res, "syntax error")
}
else {
msgHandler(objIn, function(objOut) {
if(objOut) {
var jsonOut = o2j(objOut)
res.writeHead(200, {
"Content-Type": "text/plain",
"Content-Length": jsonOut.length,
})
res.end(jsonOut)
}
}, req, res)
}
cb(body)
})
}

var isReadableFile = function(path) {
try {
if(fs.statSync(path).isFile()) {
fs.close(fs.openSync(path, "r"))
return true;

function streamOut(res, path) {
path = "docroot"+path
if(!/\.\./.test(path)) {
if(isReadableFile(path)) {
util.pump(fs.createReadStream(path), res, function(e) {
res.end("end")
})
return
}
}
catch(e) { }
return false
r500(res, "file not found")
}

var get = function(req, res) {
var u = url.parse(req.url, true),
function www(tx) {
var res = tx.res,
m = tx.req.method,
u = tx.u,
path = u.pathname
if(!/\.\./.test(req.path)) {

if(m == "GET") {
if(path == "/")
path = "/index.html"
path = "docroot"+path
if(isReadableFile(path)) {
util.pump(fs.createReadStream(path), res, function(e) {
res.end("end")
streamOut(res, path)
return;
}

r500(res, "unsupported method: "+m)
}


function api(tx, msgHandler) {
var res = tx.res,
req = tx.req,
m = tx.req.method,
json = tx.u.query.j

if(m == "POST") {
readBody(req, res, function(json) {
msgHandler(tx, j2o(json), function(msgOut) {
finish(res, o2j(msgOut))
})
})
return
}

if(m == "GET") {
if(json) {
msgHandler(tx, j2o(json), function(msgOut) {
finish(res, o2j(msgOut)) // finish(res, "jsond.recv("+o2j(msgOut)+");\n")
})
return
}
else {
streamOut(res, "/api.js")
}
return
}
r404(res)

r500(res, "unsupported method: "+m)
}


exports.createServer = function(msgHandler) {
return http.createServer(function(req, res) {
switch(req.method) {
case "POST":
post(req, res, msgHandler)
break
case "GET":
get(req, res)
break
default:
fail(res, new Error("BAD METHOD: "+req.method))
var u = url.parse(req.url, true),
tx = { req:req, res:res, u:u }

l(req.method+" "+req.url)

if(req.method == "OPTIONS") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
})
}
else {
if(/^\/api\/?$/.test(u.pathname))
api(tx, msgHandler)
else
www(tx)
}

})
}

Expand Down
15 changes: 7 additions & 8 deletions test.js
@@ -1,16 +1,15 @@

var jsond = require("./jsond")
var jsond = require("./jsond.js"),
l = console.log

var log = console.log

function msgHandler(msg, cb) {
log("incoming msg: "+JSON.stringify(msg));
function msgHandler(tx, msg, cb) {
l("incoming msg: "+JSON.stringify(msg));
msg = {r:"You said: "+msg.m}
log("sending response: "+JSON.stringify(msg));
l("sending response: "+JSON.stringify(msg));
cb(msg)
}

jsond.createServer(msgHandler).listen(30304)
jsond.createServer(msgHandler).listen(50505)

log("listening");
l("listening");

0 comments on commit d9fde60

Please sign in to comment.