From 01c6a12de51aa0252a6d624a7a968eb144655c3f Mon Sep 17 00:00:00 2001 From: Gatsbill Date: Mon, 5 Dec 2016 23:59:24 +0100 Subject: [PATCH] [perf] websocket optimisation (#453) --- lib/transports/websocket.js | 58 +++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/lib/transports/websocket.js b/lib/transports/websocket.js index 60b41ed963..7d5511b1d6 100644 --- a/lib/transports/websocket.js +++ b/lib/transports/websocket.js @@ -28,11 +28,13 @@ function WebSocket (req) { this.socket.on('message', this.onData.bind(this)); this.socket.once('close', this.onClose.bind(this)); this.socket.on('error', this.onError.bind(this)); - this.socket.on('headers', function (headers) { - self.emit('headers', headers); - }); + this.socket.on('headers', onHeaders); this.writable = true; this.perMessageDeflate = null; + + function onHeaders (headers) { + self.emit('headers', headers); + } } /** @@ -86,31 +88,37 @@ WebSocket.prototype.onData = function (data) { WebSocket.prototype.send = function (packets) { var self = this; - packets.forEach(function (packet) { - parser.encodePacket(packet, self.supportsBinary, function (data) { - debug('writing "%s"', data); - - // always creates a new object since ws modifies it - var opts = {}; - if (packet.options) { - opts.compress = packet.options.compress; - } - if (self.perMessageDeflate) { - var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length; - if (len < self.perMessageDeflate.threshold) { - opts.compress = false; - } + for (var i = 0; i < packets.length; i++) { + var packet = packets[i]; + parser.encodePacket(packet, self.supportsBinary, send); + } + + function send (data) { + debug('writing "%s"', data); + + // always creates a new object since ws modifies it + var opts = {}; + if (packet.options) { + opts.compress = packet.options.compress; + } + + if (self.perMessageDeflate) { + var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length; + if (len < self.perMessageDeflate.threshold) { + opts.compress = false; } + } + + self.writable = false; + self.socket.send(data, opts, onEnd); + } - self.writable = false; - self.socket.send(data, opts, function (err) { - if (err) return self.onError('write error', err.stack); - self.writable = true; - self.emit('drain'); - }); - }); - }); + function onEnd (err) { + if (err) return self.onError('write error', err.stack); + self.writable = true; + self.emit('drain'); + } }; /**