Skip to content

Commit 01c6a12

Browse files
billouboqdarrachequesne
authored andcommitted
[perf] websocket optimisation (#453)
1 parent 8450d03 commit 01c6a12

File tree

1 file changed

+33
-25
lines changed

1 file changed

+33
-25
lines changed

lib/transports/websocket.js

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,13 @@ function WebSocket (req) {
2828
this.socket.on('message', this.onData.bind(this));
2929
this.socket.once('close', this.onClose.bind(this));
3030
this.socket.on('error', this.onError.bind(this));
31-
this.socket.on('headers', function (headers) {
32-
self.emit('headers', headers);
33-
});
31+
this.socket.on('headers', onHeaders);
3432
this.writable = true;
3533
this.perMessageDeflate = null;
34+
35+
function onHeaders (headers) {
36+
self.emit('headers', headers);
37+
}
3638
}
3739

3840
/**
@@ -86,31 +88,37 @@ WebSocket.prototype.onData = function (data) {
8688

8789
WebSocket.prototype.send = function (packets) {
8890
var self = this;
89-
packets.forEach(function (packet) {
90-
parser.encodePacket(packet, self.supportsBinary, function (data) {
91-
debug('writing "%s"', data);
92-
93-
// always creates a new object since ws modifies it
94-
var opts = {};
95-
if (packet.options) {
96-
opts.compress = packet.options.compress;
97-
}
9891

99-
if (self.perMessageDeflate) {
100-
var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
101-
if (len < self.perMessageDeflate.threshold) {
102-
opts.compress = false;
103-
}
92+
for (var i = 0; i < packets.length; i++) {
93+
var packet = packets[i];
94+
parser.encodePacket(packet, self.supportsBinary, send);
95+
}
96+
97+
function send (data) {
98+
debug('writing "%s"', data);
99+
100+
// always creates a new object since ws modifies it
101+
var opts = {};
102+
if (packet.options) {
103+
opts.compress = packet.options.compress;
104+
}
105+
106+
if (self.perMessageDeflate) {
107+
var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
108+
if (len < self.perMessageDeflate.threshold) {
109+
opts.compress = false;
104110
}
111+
}
112+
113+
self.writable = false;
114+
self.socket.send(data, opts, onEnd);
115+
}
105116

106-
self.writable = false;
107-
self.socket.send(data, opts, function (err) {
108-
if (err) return self.onError('write error', err.stack);
109-
self.writable = true;
110-
self.emit('drain');
111-
});
112-
});
113-
});
117+
function onEnd (err) {
118+
if (err) return self.onError('write error', err.stack);
119+
self.writable = true;
120+
self.emit('drain');
121+
}
114122
};
115123

116124
/**

0 commit comments

Comments
 (0)