Skip to content

Commit 7706b12

Browse files
perf: add a "wsPreEncoded" writing option
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.
1 parent ad5306a commit 7706b12

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

lib/transports/websocket.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class WebSocket extends Transport {
7676
opts.compress = packet.options.compress;
7777
}
7878

79-
this.parser.encodePacket(packet, this.supportsBinary, data => {
79+
const send = data => {
8080
if (this.perMessageDeflate) {
8181
const len =
8282
"string" === typeof data ? Buffer.byteLength(data) : data.length;
@@ -91,7 +91,13 @@ class WebSocket extends Transport {
9191
if (err) return this.onError("write error", err.stack);
9292
this.send(packets);
9393
});
94-
});
94+
};
95+
96+
if (packet.options && typeof packet.options.wsPreEncoded === "string") {
97+
send(packet.options.wsPreEncoded);
98+
} else {
99+
this.parser.encodePacket(packet, this.supportsBinary, send);
100+
}
95101
}
96102

97103
/**

test/server.js

+21
Original file line numberDiff line numberDiff line change
@@ -2639,6 +2639,27 @@ describe("server", () => {
26392639
});
26402640
});
26412641
});
2642+
2643+
describe("pre-encoded content", () => {
2644+
it("should use the pre-encoded content", done => {
2645+
engine = listen(port => {
2646+
client = new eioc.Socket("ws://localhost:%d".s(port), {
2647+
transports: ["websocket"]
2648+
});
2649+
2650+
engine.on("connection", conn => {
2651+
conn.send("test", {
2652+
wsPreEncoded: "4test pre-encoded"
2653+
});
2654+
});
2655+
2656+
client.on("message", msg => {
2657+
expect(msg).to.be("test pre-encoded");
2658+
done();
2659+
});
2660+
});
2661+
});
2662+
});
26422663
});
26432664

26442665
describe("packet", () => {

0 commit comments

Comments
 (0)