diff --git a/client/src/Connection.ts b/client/src/Connection.ts index 41d3864..1107dae 100644 --- a/client/src/Connection.ts +++ b/client/src/Connection.ts @@ -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), diff --git a/protocol/src/index.ts b/protocol/src/index.ts index 15fb0c6..2bd4ac8 100644 --- a/protocol/src/index.ts +++ b/protocol/src/index.ts @@ -38,7 +38,7 @@ export type C2SWSOpenPayload = { url: string; }; -export type S2CWSClosePayload = { +export type WSClosePayload = { code: number; reason: string; wasClean: boolean; diff --git a/server/src/server.ts b/server/src/server.ts index 378e40c..68ddc5e 100644 --- a/server/src/server.ts +++ b/server/src/server.ts @@ -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, @@ -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; }