Lets run our “killer” application (a simple counter) in two node. At the repo, under examples\numbers, I have an appserver.js program:
It’s similar to my local example. The difference is that the top message processor is listening using a port:
/** * Host. */ var host = ajfabriq.createLocalHost(); /** * Application configuration. */ var app = host.createProcessor('numbers', 'application'); var node = app.createProcessor('processor', 'node'); node.on('decrement', function (message) { console.log("Processing number " + message.number); if (message.number <= 1) { console.log("End Processing"); return; } var number = message.number-1; this.post({ action: 'decrement', number: number }); }); host.listen(3000); host.process({ application: 'numbers', node: 'processor', action: 'decrement', number: 10 });In this code, I’m using ajfabriq.createLocalHost() instead .createProcessor(). And host.listen(3000) to accept messages from other nodes.
I run another program: appclient.js. It has the same local processors:
/** * Application configuration. */ var app = host.createProcessor('numbers', 'application'); var node = app.createProcessor('processor', 'node'); node.on('decrement', function (message) { console.log("Processing number " + message.number); if (message.number <= 1) return; var number = message.number-1; this.post({ action: 'decrement', number: number }); });But it connects to the first server, and post a new message:
var socket = new net.Socket(); socket.connect(3000, 'localhost', function() { host.connect(new ajfabriq.Channel(socket), true); socket.write(JSON.stringify({name : 'ajfmessage', message: { application: 'numbers', node: 'processor', action: 'decrement', number: 10 }})); } );ajfabriq.Channel is the bidirectional channel between two ajfabriq servers.
This server output:
![]()
Note the interchange of message between the two servers, at the beginning. They are informing their local processors, so each server knows if a message could be processed by another server.
The first server reaction:
![]()
Some of the numbers are processed by the second server, and the others are routed to the first server. The routing is a simple random choice in this demo. LocalHost objects have a new .post message:
LocalHost.prototype.post = function (message) { var hosts = [ this ]; for (var remote in this.remotes) { if (this.remotes[remote].accepts(message)) { hosts.push(this.remotes[remote]); } } var n = Math.floor(Math.random() * hosts.length); hosts[n].process(message); };Next steps: better routing, improve socket communication (large JSON messages detection and split), logging, more sample apps.
Keep tuned!
Angel “Java” Lopez
http://www.ajlopez.com