0

I have two node.js applications running side by side on my server and I wan't to send server-side messages between them in a light weight manner using native node.js (v0.10.33) module net

I intend the first application to send messages to the second. I see the console log listening...,

In the first application:

var push='';
var net=require('net');
var server=net.createServer(function(p){
    p.on('error',function(err){console.log(err);});
    push=p;
    setInterval(function(){push.write(JSON.stringify({'f':'ping','data':'stay alive'}));},1000);
    });
server.listen(8008,function(){console.log('listening...')});

//a real message might be sent later in the application (this example would need a setTimeout)
push.write(JSON.stringify({'f':'msg','data':'Hello World'}));

In the second application I see the console log open

var net=require('net');
var pull=new net.Socket();
pull.connect(8008,'127.0.0.1',function(){console.log('open');
pull.on('data',function(_){
    _=JSON.parse(_);
    if(_.f==='ping'){console.log('!!!ping!!!');}
    else{console.log(_.data);}
    });
pull.on('error',function(err){console.log('pull: '+err);});
});

I do not see any other activity though (no pings, and later after the open event, no hello world) and no errors.

If I inspect with console.dir(pull) I don't see events for accepting data ie: ondata or onmessage

What is wrong?

8DK
  • 704
  • 1
  • 5
  • 15

1 Answers1

0

Unfortunately, I must point out that this messaging scheme is fundamentally broken. You're using TCP, which provides a stream of bytes, not messages.

Despite the fact that TCP sends its data over IP packets, TCP is not a packet protocol. A TCP socket is simply a stream of data. Thus, it is incorrect to view the data event as a logical message. In other words, one socket.write on one end does not equate to a single data event on the other. A single data event might contain multiple messages, a single message, or only part of a message.

The good news is this is a problem already solved many times over. I'd recommend either:

  • Using a library meant for passing JSON messages over TCP.
  • Using something like redis as a pub-sub messaging solution (this option makes your app much easier to scale)
  • If you know that your two apps will always run on the same machine, you should use node's built-in IPC mechanism.
Community
  • 1
  • 1
josh3736
  • 139,160
  • 33
  • 216
  • 263