node-ipc/lib/client.js
2014-02-22 01:13:31 -08:00

103 lines
No EOL
2.5 KiB
JavaScript

var net = require('net'),
eventParser = require('../lib/eventParser.js'),
pubsub = require('event-pubsub');
function init(config,log){
var client={
config : config,
socket : false,
connect : connect,
emit : emit,
log : log
}
new pubsub(client);
return client;
}
function emit(type,data){
this.log('dispatching event to '.debug, this.id.variable, this.path.variable,' : ', type.data,',', data);
if(!data)
data=false;
this.socket.write(
eventParser.format(
{
type:type,
data:data
}
)
);
};
function connect(){
//init client object for scope persistance especially inside of socket events.
var client=this;
client.log('requested connection to '.debug, client.id.variable, client.path.variable);
if(!this.path){
client.log('\n\n######\nerror: '.error, client.id .info,' client has not specified socket path it wishes to connect to.'.error);
return;
}
client.socket = net.connect(
{
path:client.path
}
);
client.socket.setEncoding(this.config.encoding);
client.socket.on(
'error',
function(err){
client.log('\n\n######\nerror: '.error, err);
}
);
client.socket.on(
'connect',
function(){
client.trigger('connect');
}
);
client.socket.on(
'close',
function(){
client.log('connection closed'.notice ,client.id.variable , client.path.variable);
setTimeout(
(
function(client){
return function(){
client.connect();
}
}
)(client),
client.config.retry
);
client.trigger('disconnect');
}
);
client.socket.on(
'data',
function(data) {
client.log('## recieved events ##'.rainbow);
var events = eventParser.parse(data);
var eCount = events.length;
for(var i=0; i<eCount; i++){
var e=JSON.parse(
events[i]
);
client.log('detected event of type '.debug, e.type.data, e.data);
client.trigger(
e.type,
e.data
);
}
}
);
}
module.exports=init;