【发布时间】:2014-11-02 04:45:27
【问题描述】:
我需要实现 ZMQ 的一点扩展,其中一个 'REQ' 套接字有一个名为“.request()”的额外方法。
这个方法可以接收多个参数并且(这里我有问题)如果第一个参数是0,.request( 0, ... )只是发送消息,否则它必须等待 10 秒,如果此时我没有响应或错误,我必须 .close() 套接字并再次打开它。
所以,问题是:我如何知道在我的 ZMQ 扩展中,客户端连接到哪里才能重新连接那里我的新插座?
(我也需要使用承诺,这就是为什么在代码中出现“Q.deffer()”和所有这些东西)
var zmq = require('./pzmq');
var rq = zmq.socket('req');
var counter=0;
function onSuccess(msg) {
console.log('Response: '+msg);
console.log(msg instanceof Array);
}
function onError(err) {
console.log('Error: '+err);
}
rq.connect('tcp://127.0.0.1:8888');
console.log(rq.indentity);
// The "Hello" string is sent every second
reply = rq.request(0, counter++,4);
reply.then(onSuccess,onError);
这里有我的 ZMQ 小扩展,名为 pzmq:
var zmq = require('zmq');
var Q = require('bluebird');
// Save the original socket method, we need it
var socket = zmq.socket;
// Create and store the wrapper method
zmq.socket = function(kind) {
// it uses the original method anyways, to get a zmq socket
var so = socket.call(zmq, kind);
if (kind == 'req') {
// if a 'req' socket is requested, then we add the extra method 2
so.request = request;
}
return so;
};
function request() {
var d = Q.defer();
var that = this;
var onResponse = function () {
console.log(arguments instanceof Array);
d.resolve(Array.prototype.slice.call(arguments));
that.removeListener('error', onError);
};
var onError = function (e) {
d.reject(e);
that.removeListener('message', onResponse);
};
this.once('message', onResponse); // set up the handler for only one message
this.once('error', onError); // set up the handler for only one
var argumentos = Array.prototype.slice.call(arguments);
var tiempo = argumentos[0];
if (tiempo==0){
this.send(argumentos);
}else{
//HERE IS THE PROBLEM
}
return d.promise;
}
【问题讨论】:
标签: javascript sockets zeromq