File tree Expand file tree Collapse file tree 2 files changed +41
-3
lines changed Expand file tree Collapse file tree 2 files changed +41
-3
lines changed Original file line number Diff line number Diff line change @@ -60,6 +60,8 @@ function MqttClient(stream, options) {
60
60
this . pingTimer = null ;
61
61
// Is the client connected?
62
62
this . connected = false ;
63
+ // Packet queue
64
+ this . queue = [ ] ;
63
65
64
66
// Inflight messages
65
67
this . inflight = {
@@ -88,9 +90,21 @@ function MqttClient(stream, options) {
88
90
// Setup ping timer
89
91
this . on ( 'connect' , this . _setupPingTimer ) ;
90
92
91
- // Mark the client as connected
93
+ // Send queued packets
92
94
this . on ( 'connect' , function ( ) {
93
95
that . connected = true ;
96
+
97
+ var queue = that . queue
98
+ , length = queue . length ;
99
+
100
+ for ( var i = 0 ; i < length ; i += 1 ) {
101
+ that . _sendPacket (
102
+ queue [ i ] . type ,
103
+ queue [ i ] . packet ,
104
+ queue [ i ] . cb
105
+ ) ;
106
+ }
107
+ that . queue = [ ] ;
94
108
} ) ;
95
109
96
110
// Handle incoming publish
@@ -298,12 +312,20 @@ MqttClient.prototype.end = function() {
298
312
}
299
313
} ;
300
314
315
+ MqttClient . prototype . _sendPacket = function ( type , packet , cb ) {
316
+ if ( this . connected ) {
317
+ this . conn [ type ] ( packet ) ;
318
+ if ( cb ) cb . call ( this ) ;
319
+ } else {
320
+ this . queue . push ( { type : type , packet : packet , cb : cb } ) ;
321
+ }
322
+ } ;
323
+
301
324
/**
302
325
* _setupPingTimer
303
326
*
304
327
* @api private
305
328
*/
306
-
307
329
MqttClient . prototype . _setupPingTimer = function ( ) {
308
330
// No ping
309
331
if ( this . options . keepalive === 0 ) {
Original file line number Diff line number Diff line change @@ -211,7 +211,23 @@ describe('MqttClient', function () {
211
211
} ) ;
212
212
213
213
describe ( 'publishing' , function ( ) {
214
- it ( 'should publish a message' , function ( done ) {
214
+ it ( 'should queue message until connected' , function ( done ) {
215
+ var client = createClient ( port ) ;
216
+
217
+ client . publish ( 'test' , 'test' ) ;
218
+ client . queue . length . should . equal ( 1 ) ;
219
+
220
+ client . once ( 'connect' , function ( ) {
221
+ client . queue . length . should . equal ( 0 ) ;
222
+ done ( ) ;
223
+ } ) ;
224
+
225
+ this . server . once ( 'client' , function ( client ) {
226
+ client . once ( 'connect' , function ( packet ) {
227
+ client . connack ( { returnCode : 0 } ) ;
228
+ } ) ;
229
+ } ) ;
230
+ } ) ;
215
231
var client = createClient ( port )
216
232
, payload = 'test'
217
233
, topic = 'test' ;
You can’t perform that action at this time.
0 commit comments