如何控制node.js mqtt库中的重新连接

时间:2013-12-07 21:11:52

标签: node.js mqtt

我使用node.js mqtt library连接互联网mqtt服务

var name = '/#';
var mqttclient = mqtt.createClient(1883, service.getHost(),{username:"" ,password: service.getKey() });
mqttclient.on('connect', function onConnect(){
   winston.info('MQTT Connected'.green, '/'+service.getPattern()+name);
   mqttclient.subscribe('/'+service.getPattern()+name);
   mqttclient.on('message', handleMessage);
}); 

 mqttclient.on('disconnect', onConnect);
 mqttclient.on('close', onClose);
 mqttclient.on('error', onError);

 function onDisconnect(packet){
        winston.info('MQTT MONITOR disconnect!'+packet);            
 }

 function onClose(packet){
        winston.info('MQTT MONITOR close!'+packet); 
 }

 function onError(err){
        winston.error('MQTT MONITORerror!'+err);        
 }

当我的互联网连接断开或认证用户名/密码错误时,mqtt库会发出close事件,只要mqtt.end(),这个事件就会被连续触发。

2013-12-07T18:36:53.835Z - info: MQTT MONITOR close!false
2013-12-07T18:36:54.835Z - info: MQTT MONITOR close!false
2013-12-07T18:36:55.832Z - info: MQTT MONITOR close!false
2013-12-07T18:36:56.833Z - info: MQTT MONITOR close!false
2013-12-07T18:36:57.831Z - info: MQTT MONITOR close!false
2013-12-07T18:36:58.847Z - info: MQTT MONITOR close!false
2013-12-07T18:36:59.842Z - info: MQTT MONITOR close!false
2013-12-07T18:37:00.833Z - info: MQTT MONITOR close!false
2013-12-07T18:37:01.832Z - info: MQTT MONITOR close!false
2013-12-07T18:37:02.847Z - info: MQTT MONITOR close!false
在我看来,mqtt close callback无法告诉我发生了什么样的错误,例如身份验证错误或主机无法达到错误。

此外,我假设有重新连接策略。如何在mqtt代码中控制这种重新连接策略?

1 个答案:

答案 0 :(得分:0)

查看您的代理日志以查看此行为的线索。

在MQTT协议中,keepalive值定义了向代理发送ping消息的速率。

将各种客户端连接到同一代理时,也使用不同的clientid