Skip to content

Commit

Permalink
Randomly generate packet ids
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Rudd committed Jun 9, 2013
1 parent d455178 commit 148c0a1
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions lib/client.js
Expand Up @@ -52,8 +52,6 @@ function MqttClient(stream, options) {
this.conn = new Connection(stream);
this.stream = this.conn.stream;

// Next messageId
this.nextId = 0;
// Ping timer, setup in _setupPingTimer
this.pingTimer = null;
// Is the client connected?
Expand Down Expand Up @@ -187,7 +185,7 @@ function(topic, message, opts, callback) {
payload: message,
qos: opts.qos,
retain: opts.retain,
messageId: this.nextId
messageId: this._nextId()
}

this._sendPacket('publish', packet, function () {
Expand All @@ -198,11 +196,11 @@ function(topic, message, opts, callback) {
break;
case 1:
// Add to puback callbacks
this.inflight.puback[this.nextId++] = callback;
this.inflight.puback[packet.messageId] = callback;
break;
case 2:
// Add to pubrec callbacks
this.inflight.pubrec[this.nextId++] = callback;
this.inflight.pubrec[packet.messageId] = callback;
break
default:
break;
Expand Down Expand Up @@ -256,13 +254,13 @@ function(topic, opts, callback) {
var packet = {
subscriptions: subs,
qos: 1,
messageId: this.nextId,
retain: false,
dup: false
dup: false,
messageId: this._nextId()
};

this._sendPacket('subscribe', packet, function () {
this.inflight.suback[this.nextId++] = {
this.inflight.suback[packet.messageId] = {
callback: callback,
packet: packet
};
Expand All @@ -283,7 +281,7 @@ function(topic, opts, callback) {
*/
MqttClient.prototype.unsubscribe = function(topic, callback) {
callback = callback || nop;
var packet = {messageId: this.nextId};
var packet = {messageId: this._nextId()};

if ('string' === typeof topic) {
packet.unsubscriptions = [topic];
Expand All @@ -292,7 +290,7 @@ MqttClient.prototype.unsubscribe = function(topic, callback) {
}

this._sendPacket('unsubscribe', packet, function () {
this.inflight.unsuback[this.nextId++] = callback;
this.inflight.unsuback[packet.messageId] = callback;
});

return this;
Expand Down Expand Up @@ -490,3 +488,10 @@ MqttClient.prototype._handlePubrel = function(packet) {
this.conn.pubcomp({messageId: mid});
this.emit('message', pub.topic, pub.payload, pub);
};

/**
* _nextId
*/
MqttClient.prototype._nextId = function() {
return Math.floor(Math.random() * 65535);
};

0 comments on commit 148c0a1

Please sign in to comment.