Skip to content

Commit

Permalink
perf: add a "wsPreEncoded" writing option
Browse files Browse the repository at this point in the history
This option will be used when broadcasting a packet to multiple clients,
in order to only encode the packet once.

Usage:

```js
socket.write("test", {
  wsPreEncoded: "4test"
});
```

Note: pre-encoding the content with HTTP long-polling is a bit harder,
since the concatenation of the packets is specific to each client.
  • Loading branch information
darrachequesne committed May 4, 2021
1 parent ad5306a commit 7706b12
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/transports/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class WebSocket extends Transport {
opts.compress = packet.options.compress;
}

this.parser.encodePacket(packet, this.supportsBinary, data => {
const send = data => {
if (this.perMessageDeflate) {
const len =
"string" === typeof data ? Buffer.byteLength(data) : data.length;
Expand All @@ -91,7 +91,13 @@ class WebSocket extends Transport {
if (err) return this.onError("write error", err.stack);
this.send(packets);
});
});
};

if (packet.options && typeof packet.options.wsPreEncoded === "string") {
send(packet.options.wsPreEncoded);
} else {
this.parser.encodePacket(packet, this.supportsBinary, send);
}
}

/**
Expand Down
21 changes: 21 additions & 0 deletions test/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2639,6 +2639,27 @@ describe("server", () => {
});
});
});

describe("pre-encoded content", () => {
it("should use the pre-encoded content", done => {
engine = listen(port => {
client = new eioc.Socket("ws://localhost:%d".s(port), {
transports: ["websocket"]
});

engine.on("connection", conn => {
conn.send("test", {
wsPreEncoded: "4test pre-encoded"
});
});

client.on("message", msg => {
expect(msg).to.be("test pre-encoded");
done();
});
});
});
});
});

describe("packet", () => {
Expand Down

0 comments on commit 7706b12

Please # to comment.