diff --git a/lib/Sender.js b/lib/Sender.js index 73914fc88..2d846e509 100644 --- a/lib/Sender.js +++ b/lib/Sender.js @@ -54,9 +54,8 @@ Sender.prototype.close = function(code, data, mask, cb) { if (dataBuffer.length > 2) dataBuffer.write(data, 2); var self = this; - this.messageHandlers.push(function(callback) { + this.messageHandlers.push(function() { self.frameAndSend(0x8, dataBuffer, true, mask); - callback(); if (typeof cb == 'function') cb(); }); this.flush(); @@ -71,9 +70,8 @@ Sender.prototype.close = function(code, data, mask, cb) { Sender.prototype.ping = function(data, options) { var mask = options && options.mask; var self = this; - this.messageHandlers.push(function(callback) { + this.messageHandlers.push(function() { self.frameAndSend(0x9, data || '', true, mask); - callback(); }); this.flush(); }; @@ -87,9 +85,8 @@ Sender.prototype.ping = function(data, options) { Sender.prototype.pong = function(data, options) { var mask = options && options.mask; var self = this; - this.messageHandlers.push(function(callback) { + this.messageHandlers.push(function() { self.frameAndSend(0xa, data || '', true, mask); - callback(); }); this.flush(); }; @@ -117,7 +114,13 @@ Sender.prototype.send = function(data, options, cb) { var compressFragment = this.compress; var self = this; - this.messageHandlers.push(function(callback) { + this.messageHandlers.push(function() { + if (!data || !compressFragment) { + self.frameAndSend(opcode, data, finalFragment, mask, compress, cb); + return; + } + + self.processing = true; self.applyExtensions(data, finalFragment, compressFragment, function(err, data) { if (err) { if (typeof cb == 'function') cb(err); @@ -125,7 +128,8 @@ Sender.prototype.send = function(data, options, cb) { return; } self.frameAndSend(opcode, data, finalFragment, mask, compress, cb); - callback(); + self.processing = false; + self.flush(); }); }); this.flush(); @@ -257,21 +261,9 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData, */ Sender.prototype.flush = function() { - if (this.processing) return; - - var handler = this.messageHandlers.shift(); - if (!handler) return; - - this.processing = true; - - var self = this; - - handler(function() { - process.nextTick(function() { - self.processing = false; - self.flush(); - }); - }); + while (!this.processing && this.messageHandlers.length) { + this.messageHandlers.shift()(); + } }; /** @@ -281,14 +273,10 @@ Sender.prototype.flush = function() { */ Sender.prototype.applyExtensions = function(data, fin, compress, callback) { - if (compress && data) { - if ((data.buffer || data) instanceof ArrayBuffer) { - data = getArrayBuffer(data); - } - this.extensions[PerMessageDeflate.extensionName].compress(data, fin, callback); - } else { - callback(null, data); + if ((data.buffer || data) instanceof ArrayBuffer) { + data = getArrayBuffer(data); } + this.extensions[PerMessageDeflate.extensionName].compress(data, fin, callback); }; module.exports = Sender;