Real-time messaging using NodeJS for multiple processes

I am trying to implement an API that interacts with a NodeJS server for real-time messaging. Now that a NodeJS application is deployed in a scalable environment such as Heroku , several instances of this application can work.

Is it possible to create a node application so that all clients who subscribe to the "message channel" receive this message, although several instances of the node are executed - and, therefore, several copies of this channel?

+1
source share
1 answer

Check out zeromq , it should provide some simple, high-performance IPC abstractions to do what you want. In particular, the pub / sub example is useful.

The main task that I imagine, not knowing anything about how Heroku spawns multiple server instances, will be the logic of determining who is the publisher (the rest of the instances will be subscribers). Say, for the sake of argument, that your hosting provider provides you with an environment variable named INSTANCE_NUM , which is an integer in [0,1024] indicating the process instance number; therefore, we say that instance zero is a message publisher.

 var zmq = require('zeromq') if (process.env['INSTANCE_NUM'] === '0') { // I'm the publisher. var emitter = getEventEmitter(); // eg an HttpServer. var pub = zmq.createSocket('pub'); pub.bindSync('tcp://*:5555'); emitter.on('someEvent', function(data) { pub.send(data); }); } else { // I'm a subscriber. var sub = zmq.createSocket('sub'); sub.subscribe(''); sub.on('message', function(data) { // Handle the event data... }); sub.connect('tcp://localhost:5555'); } 

Please note that I am new to zeromq and the above code is not fully tested, just for demonstration.

0
source

Source: https://habr.com/ru/post/1412324/


All Articles