Skip to content

Commit

Permalink
[perf] websocket optimisation (#453)
Browse files Browse the repository at this point in the history
  • Loading branch information
billouboq authored and darrachequesne committed Dec 5, 2016
1 parent 8450d03 commit 01c6a12
Showing 1 changed file with 33 additions and 25 deletions.
58 changes: 33 additions & 25 deletions lib/transports/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

/**
Expand Down Expand Up @@ -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');
}
};

/**
Expand Down

0 comments on commit 01c6a12

Please sign in to comment.