zeromq.node icon indicating copy to clipboard operation
zeromq.node copied to clipboard

no pattern for multiple requests

Open awb99 opened this issue 9 years ago • 1 comments

I am still new to node-zmq, but I understand req-res is synchronos; or perhaps in other words there is a link between request and response. I dont see any way how to associate request and response.

The code below is a simple express.js route, that will serve as a bridge of a REST interface to a ZMQ response server.

Either the unsubscribe on message is missing; or there should be a function send( data, callback). Currently there is only send (data);

This is the code:

var zmq = require('zmq') , sock = zmq.socket('req');

sock.connect(zmqServerl);

app.get('/api/data', function(req, res) { console.log('requesting data'); sock.send('data'); sock.on('message', function(msg) { var json= msg.toString() console.log('got ZMQ reply data '); res.send (json); }); });

Regard Andreas

awb99 avatar Jan 27 '16 20:01 awb99

The problem is that you are binding a message handler on each request against /api/data - also note that unless you know otherwise, there isn't a guarantee that there will be a single request against that url before a response is sent from the server. You should consider using a dealer/router socket combo to mitigate that, which allow asynchronous messaging (multiple in either direction).

Just for reference, here's what would need to be changed to resolve the multiple message listeners:

var zmq = require('zmq'),
    sock = zmq.socket('req');

sock.connect(zmqServerl);

app.get('/api/data', function (req, res) {
    console.log('requesting data');

    var handler = function (msg) {
        var json = msg.toString()
        console.log('got ZMQ reply data ');
        res.send(json);
        sock.removeListener('message', handler);
    };

    sock.on('message', handler);

    sock.send('data');
});

OR bind the listener outside the express endpoint:

var zmq = require('zmq'),
    sock = zmq.socket('req');

sock.connect(zmqServerl);

var handler = function (msg) {
    var json = msg.toString()
    console.log('got ZMQ reply data ');
    res.send(json);
    sock.removeListener('message', handler);
};

sock.on('message', handler);

app.get('/api/data', function (req, res) {
    console.log('requesting data');
    sock.send('data');
});

quinndiggity avatar May 03 '16 16:05 quinndiggity