Skip to content

Commit

Permalink
feat: favor WebTransport over WebSocket
Browse files Browse the repository at this point in the history
This commit ensures that when there are multiple possible upgrades
(like WebSocket and WebTransport), then the WebTransport is favored and
the other upgrades are delayed.

Following 7195c0f
  • Loading branch information
darrachequesne committed Jun 16, 2023
1 parent 13d08bc commit 9d37b16
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export class Socket extends Emitter<
public writeBuffer: Packet[] = [];

private prevBufferLen: number;
private upgrades;
private upgrades: string[];
private pingInterval: number;
private pingTimeout: number;
private pingTimeoutTimer: NodeJS.Timer;
Expand Down Expand Up @@ -601,7 +601,19 @@ export class Socket extends Emitter<
this.once("close", onclose);
this.once("upgrading", onupgrade);

transport.open();
if (
this.upgrades.indexOf("webtransport") !== -1 &&
name !== "webtransport"
) {
// favor WebTransport
this.setTimeoutFn(() => {
if (!failed) {
transport.open();
}
}, 200);
} else {
transport.open();
}
}

/**
Expand Down
24 changes: 24 additions & 0 deletions test/webtransport.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,30 @@ describe("WebTransport", () => {
);
});

it("should favor WebTransport over WebSocket", (done) => {
setup(
{
transports: ["polling", "websocket", "webtransport"],
},
({ engine, h3Server, certificate }) => {
const httpServer = createServer();
engine.attach(httpServer);
httpServer.listen(h3Server.port);

const socket = createSocket(h3Server.port, certificate, {
transports: ["polling", "websocket", "webtransport"],
});

socket.on("upgrade", (transport) => {
expect(transport.name).to.eql("webtransport");

httpServer.close();
success(engine, h3Server, done);
});
}
);
});

it("should send ping/pong packets", (done) => {
setup(
{
Expand Down

0 comments on commit 9d37b16

Please sign in to comment.