FreeBSDでnode.js+ZeroMQ

node.js+ZeroMQでメッセージング・ドリブンのイベント駆動プログラミングをやってみました.

ZeroMQのnode.jsバインディングのインストール.

> wget http://download.zeromq.org/zeromq-2.1.10.tar.gz
> tar xvf zeromq-2.1.10.tar.gz
> cd zeromq-2.1.10
> ./configure --prefix=/usr/local
> make
> su
# make install
exit
> wget http://prdownloads.sourceforge.net/e2fsprogs/e2fsprogs-1.41.14.tar.gz
> tar xvr e2fsprogs-1.41.14.tar.gz
> cd e2fsprogs-1.41.14
> ./configure --prefix=/usr/local --enable-elf-shlibs --enable-bsd-shlibs
> cd lib/uuid/
> gmake
> su
# gmake install
# exit
exit
>cd
> wget --no-check-certificate https://github.com/JustinTulloss/zeromq.node/tarball/master
> tar xvf master
> cd JustinTulloss-zeromq.node-4da20cd/
> setenv PKG_CONFIG_PATH /usr/local/lib/pkgconfig
> setenv NODE_PATH /usr/local/node/zmq
> node-waf configure build
> su
# node-waf install
'install' finished successfully (0.074s)
# cp -pvr . /usr/local/node/zmq/
# exit
exit
> 

そして,インストールした2台のマシンで次のようなnode.jsのサンプルを走らせてみます.

var context = require('zmq');
var os = require('os');

console.log("Starting ...");

var publisher = context.createSocket('pub');
publisher.bindSync("tcp://*:5555");

var subscriber = context.createSocket('sub');
subscriber.subscribe("");
subscriber.connect("tcp://相手マシン名:5555");

subscriber.on('message', function(data)
{
  console.log(os.hostname()+":Thank you for message ["+data+"]");
  if(data.toString().substr(0,4)!="Your")
  {
     var mes = "Your message was ["+data+"]";
     publisher.send(mes);
  }
  console.log("process ends");
  process.exit(0);
});
setInterval(function(){
    var now = os.hostname()+":"+Math.random().toString();
    console.log("My message is ["+now+"]");
    publisher.send(now);
}, Math.random()*10000);

こうすると,2台のマシンで乱数によって最初に会話を始めた方(「My message is」を出した方)が相手のマシンによって受け止められて(「Thank you for message [My message is ...」),メッセージを受け取った方は「Your message was を出力して停止,メッセージを出した方は「Your..」を受け取るのでやはり停止します.
要は,エージェントが会話します.
実行例は以下です.

マシンA:
> node demo.js
Starting ...
My message is [マシンA:0.007318727904930711]
マシンA:Thank you for message [Your message was マシンA:0.007318727904930711]]
process ends

マシンB:
> node demo.js
Starting ...
マシンB:Thank you for message [マシンA:0.007318727904930711]
process ends

メッセージが,
マシンA:0.007318727904930711

Your message was マシンA:0.007318727904930711

マシンA:Thank you for message [Your message was マシンA:0.007318727904930711]]

という感じで会話されてます.