Permalink
Browse files

very basic .listen() part with a README

  • Loading branch information...
substack committed Jun 8, 2010
0 parents commit 979efc1887de667952a1162d3295c89a3698d5b8
Showing with 104 additions and 0 deletions.
  1. +18 −0 README
  2. +86 −0 dnode.js
18 README
@@ -0,0 +1,18 @@
+Simple asynchronous remote method invocation for node.js.
+Note: not everything is implemented yet
+
+Example:
+ var DNode = require('dnode').DNode;
+ var sys = require('sys');
+
+ // server-side:
+ DNode({
+ timesTen : function (n) { return n * 10 }
+ }).listen(6060);
+
+ // client-side:
+ var dnode = DNode().connect(6060);
+ dnode.timesTen(5, function (res) {
+ sys.log(res); // 50, computation executed on the server
+ });
+
@@ -0,0 +1,86 @@
+var net = require('net');
+var BufferList = require('bufferlist').BufferList;
+var sys = require('sys');
+
+exports.DNode = DNode;
+
+function DNode (wrapper) {
+ if (!(this instanceof DNode)) return new DNode(wrapper);
+
+ // share an object or a function that returns an object
+ var f = wrapper instanceof Function
+ ? wrapper
+ : function () { return wrapper }
+ ;
+
+ this.connect = function () {
+ var args = [].concat.apply([],arguments);
+ var kwargs = args.filter(function (x) {
+ return typeof(x) == 'object'
+ })[0] || {};
+
+ var host = args.filter(function (x) {
+ return typeof(x) == 'string'
+ })[0] || kwargs.host;
+
+ var port = args.filter(function (x) {
+ return typeof(x) == 'number'
+ })[0] || kwargs.port;
+
+ };
+
+ this.listen = function () {
+ var args = [].concat.apply([],arguments);
+ var kwargs = args.filter(function (x) {
+ return typeof(x) == 'object'
+ })[0] || {};
+
+ var host = args.filter(function (x) {
+ return typeof(x) == 'string'
+ })[0] || kwargs.host;
+
+ var port = args.filter(function (x) {
+ return typeof(x) == 'number'
+ })[0] || kwargs.port;
+
+ var bufferList = new BufferList;
+ net.createServer(function (sock) {
+ var instance = f();
+
+ sock.addListener('data', function (buf) {
+ bufferList.push(buf);
+ var n = buf.toString().indexOf('\n');
+ if (n >= 0) {
+ var i = bufferList.length - (buf.length - n);
+ var line = bufferList.take(i); // up to the \n
+ bufferList.advance(i + 1); // past the \n
+
+ var cmd = JSON.parse(line);
+ var obj = instance[cmd.name];
+
+ if (typeof(obj) in 'string number undefined'.split(' ')) {
+ sock.write(JSON.stringify({
+ "id" : cmd.id,
+ "result" : obj,
+ }) + '\n');
+ }
+ else if (obj instanceof Function) {
+ var res = obj.apply(instance, cmd.args);
+ sock.write(JSON.stringify({
+ "id" : cmd.id,
+ "result" : res, // todo: wrap references
+ }) + '\n');
+ }
+ else {
+ sock.write(JSON.stringify({
+ "id" : cmd.id,
+ "result" : obj, // todo: wrap references
+ }) + '\n');
+ }
+ }
+ });
+
+ }).listen(port, host);
+ };
+};
+

0 comments on commit 979efc1

Please sign in to comment.