impl C2S ws close

This commit is contained in:
Spencer Pogorzelski 2023-08-14 13:56:39 -07:00
parent 321bbf9734
commit 8babd1896e
3 changed files with 14 additions and 6 deletions

View file

@ -175,7 +175,6 @@ export class Connection {
return {
send: (data) => {
console.log("Reached Connection.ts send!");
if (!this.openSockets[seq]) {
throw new Error("send on closed socket");
}
@ -210,7 +209,8 @@ export class Connection {
throw new Error("Unexpected type passed to send");
},
close: (code?: number, reason?: string) => {
const payload = JSON.stringify({ code, reason });
const payload = { code, reason };
const payloadJSON = JSON.stringify(payload);
this.send(
seq,
new TextEncoder().encode(payload),

View file

@ -38,7 +38,7 @@ export type C2SWSOpenPayload = {
url: string;
};
export type S2CWSClosePayload = {
export type WSClosePayload = {
code: number;
reason: string;
wasClean: boolean;

View file

@ -8,7 +8,7 @@ import {
ProtoBareHeaders,
S2CRequestType,
S2CRequestTypes,
S2CWSClosePayload,
WSClosePayload,
} from "protocol";
import { Readable } from "stream";
import { BareError, bareFetch, options } from "./http";
@ -160,7 +160,7 @@ export class AdriftServer {
this._sendSimpleRes(seq, S2CRequestTypes.WSOpen);
}
sendWSClose(seq: number, payload: S2CWSClosePayload) {
sendWSClose(seq: number, payload: WSClosePayload) {
this._sendJSONRes(seq, S2CRequestTypes.WSClose, payload);
}
@ -241,6 +241,10 @@ export class AdriftServer {
const ws = (this.sockets[seq] = new WebSocket(payload.url));
ws.binaryType = "arraybuffer";
// TODO v important: onerror
ws.onerror = (e) => {
console.log("ws onerror", e);
this.sendWSClose(seq, { code: 1006, reason: "", wasClean: false });
};
ws.onopen = () => {
this.sendWSOpen(seq);
};
@ -250,6 +254,7 @@ export class AdriftServer {
reason: e.reason,
wasClean: e.wasClean,
});
delete this.sockets[seq];
};
(ws as any).onmessage = (
dataOrEvent: ArrayBuffer | MessageEvent<any>,
@ -300,7 +305,10 @@ export class AdriftServer {
case C2SRequestTypes.WSClose: {
const socket = this.sockets[seq];
if (!socket) return;
socket.close();
const payload: WSClosePayload | undefined =
AdriftServer.tryParseJSONPayload(msg.slice(cursor));
if (!payload) return;
socket.close(payload.code || 1005, payload.reason || "");
break;
}