Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[perf] websocket optimisation #453

Merged
merged 5 commits into from
Dec 5, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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