add server ws.terminate (#9693)

* add server ws.terminate

* [autofix.ci] apply automated fixes

* it has to be blazing fast

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
This commit is contained in:
dave caruso
2024-03-28 18:17:55 -07:00
committed by GitHub
parent aaef6d350a
commit d113803777
2 changed files with 36 additions and 0 deletions

View File

@@ -700,6 +700,23 @@ class BunWebSocketMocked extends EventEmitter {
this.#ws.close(code, reason);
}
}
terminate() {
let state = this.#state;
if (state === 3) return;
if (state === 0) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
let ws = this.#ws;
if (ws) {
this.#state = WebSocket.CLOSING;
ws.terminate();
}
}
get binaryType() {
return this.#binaryType;
}

View File

@@ -276,6 +276,25 @@ describe("WebSocketServer", () => {
new WebSocket("ws://localhost:" + wss.address().port);
await promise;
});
it("sockets can be terminated", async () => {
const wss = new WebSocketServer({ port: 0 });
const { resolve, reject, promise } = Promise.withResolvers();
wss.on("connection", ws => {
ws.on("close", () => {
resolve();
});
try {
ws.terminate();
} catch (err) {
reject(err);
}
});
new WebSocket("ws://localhost:" + wss.address().port);
await promise;
});
});
describe("Server", () => {