Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 3 additions & 5 deletions packages/engine.io-client/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
22 changes: 22 additions & 0 deletions packages/engine.io-client/test/arraybuffer/polling.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
});
});
});