diff --git a/packages/engine.io-client/lib/util.ts b/packages/engine.io-client/lib/util.ts index bfb6a59aa5..db9eb0b924 100644 --- a/packages/engine.io-client/lib/util.ts +++ b/packages/engine.io-client/lib/util.ts @@ -23,16 +23,14 @@ export function installTimerFunctions(obj, opts) { } } -// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) -const BASE64_OVERHEAD = 1.33; - // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 export function byteLength(obj) { if (typeof obj === "string") { return utf8Length(obj); } - // arraybuffer or blob - return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); + // arraybuffer or blob, which are base64 encoded with HTTP long-polling: each group of 3 bytes gives 4 characters, + // and the last group is padded (https://en.wikipedia.org/wiki/Base64) + return Math.ceil((obj.byteLength || obj.size) / 3) * 4; } function utf8Length(str) { diff --git a/packages/engine.io-client/test/arraybuffer/polling.js b/packages/engine.io-client/test/arraybuffer/polling.js index b182adc7b6..45cb5b121f 100644 --- a/packages/engine.io-client/test/arraybuffer/polling.js +++ b/packages/engine.io-client/test/arraybuffer/polling.js @@ -93,4 +93,26 @@ describe("arraybuffer", function () { }); }); }); + + it("should use the exact base64 length when merging binary packets", (done) => { + const socket = new Socket({ transports: ["polling"] }); + // both packets are buffered before the handshake, so they are flushed together: + // "bAA==" (5) + separator (1) + "4" + "a" x 94 (95) = 101 bytes, above the maxPayload value of 100 + socket.send(new Uint8Array(1)); + socket.send(repeat("a", 94)); + + const onClose = (reason) => done(new Error(`unexpected close: ${reason}`)); + socket.on("close", onClose); + + let count = 0; + socket.on("message", (data) => { + if (data === "hi") return; + count++; + if (count === 2) { + socket.off("close", onClose); + socket.close(); + done(); + } + }); + }); });