@@ -90,8 +90,14 @@ Polling.prototype.onPollRequest = function (req, res) {
90
90
req . cleanup = cleanup ;
91
91
req . on ( 'close' , onClose ) ;
92
92
93
- this . buffer = false ;
94
- this . flush ( ) ;
93
+ this . writable = true ;
94
+ this . emit ( 'drain' ) ;
95
+
96
+ // if we're still writable but had a pending close, trigger an empty send
97
+ if ( this . writable && this . shouldClose ) {
98
+ debug ( 'triggering empty send to append close packet' ) ;
99
+ this . send ( [ ] ) ;
100
+ }
95
101
}
96
102
} ;
97
103
@@ -162,41 +168,22 @@ Polling.prototype.onData = function (data) {
162
168
} ;
163
169
164
170
/**
165
- * Flushes buffers.
166
- *
167
- * @api private
168
- */
169
-
170
- Polling . prototype . flush = function ( ) {
171
- if ( this . writeBuffer ) {
172
- this . write ( parser . encodePayload ( this . writeBuffer ) ) ;
173
- this . writeBuffer = null ;
174
- this . emit ( 'drain' ) ;
175
- }
176
- } ;
177
-
178
- /**
179
- * Writes a packet.
171
+ * Writes a packet payload.
180
172
*
181
173
* @param {Object } packet
182
- * @param {Function } called when the packet is dispatched
183
174
* @api private
184
175
*/
185
176
186
- Polling . prototype . send = function ( packet , fn ) {
187
- if ( this . buffer ) {
188
- if ( ! this . writeBuffer ) {
189
- this . writeBuffer = [ ] ;
190
- }
191
-
192
- debug ( 'poll buffering packet: type %s | data %s' , packet . type , packet . data ) ;
193
- this . writeBuffer . push ( packet ) ;
194
- if ( fn ) this . once ( 'drain' , fn ) ;
195
- } else {
196
- debug ( 'poll writing packet: type %s | data %s' , packet . type , packet . data ) ;
197
- this . write ( parser . encodePayload ( [ packet ] ) ) ;
198
- if ( fn ) fn ( ) ;
177
+ Polling . prototype . send = function ( packets ) {
178
+ debug ( 'polling writing packets' , JSON . stringify ( packets ) ) ;
179
+ if ( this . shouldClose ) {
180
+ debug ( 'appending close packet to payload' ) ;
181
+ packets . push ( { type : 'close' } ) ;
182
+ this . shouldClose ( ) ;
183
+ this . shouldClose = null ;
199
184
}
185
+
186
+ this . write ( parser . encodePayload ( packets ) ) ;
200
187
} ;
201
188
202
189
/**
@@ -209,7 +196,7 @@ Polling.prototype.send = function (packet, fn) {
209
196
Polling . prototype . write = function ( data ) {
210
197
this . doWrite ( data ) ;
211
198
this . req . cleanup ( ) ;
212
- this . buffer = true ;
199
+ this . writable = false ;
213
200
} ;
214
201
215
202
/**
@@ -225,5 +212,11 @@ Polling.prototype.doClose = function (fn) {
225
212
this . dataReq . abort ( ) ;
226
213
}
227
214
228
- this . send ( { type : 'close' } , fn ) ;
215
+ if ( this . writable ) {
216
+ debug ( 'polling transport is writable - closing right away' ) ;
217
+ this . send ( [ { type : 'close' } ] ) ;
218
+ } else {
219
+ debug ( 'polling transport not writable - marking that we should close' ) ;
220
+ this . shouldClose = fn ;
221
+ }
229
222
} ;
0 commit comments