diff --git a/lib/transports/websocket.js b/lib/transports/websocket.js index cb6a566ca..4ca184d1a 100644 --- a/lib/transports/websocket.js +++ b/lib/transports/websocket.js @@ -82,11 +82,44 @@ WS.prototype.doOpen = function(){ */ WS.prototype.write = function(packets){ + var self = this; + this.writable = false; + // encodePacket efficient as it uses WS framing + // no need for encodePayload for (var i = 0, l = packets.length; i < l; i++) { this.socket.send(parser.encodePacket(packets[i])); } + function ondrain() { + self.writable = true; + self.emit('drain'); + } + // check periodically if we're done sending + if ('bufferedAmount' in this.socket) { + this.bufferedAmountId = this.setInterval(function() { + if (self.socket.bufferedAmount == 0) { + clearInterval(self.bufferedAmountId); + ondrain(); + } + }, 50); + } else { + // fake drain + // defer to next tick to allow Socket to clear writeBuffer + setTimeout(ondrain, 0); + } }; +/** + * Called upon close + * + * @api private + */ + +WS.prototype.onClose = function(){ + // stop checking to see if websocket is done sending buffer + clearInterval(this.bufferedAmountId); + Transport.prototype.onClose.call(this); +} + /** * Closes socket. *