From 2022a4cee8b8715b0ce2c82b4093104603803cfb Mon Sep 17 00:00:00 2001 From: Spencer Pogorzelski <34356756+Scoder12@users.noreply.github.com> Date: Fri, 11 Aug 2023 16:57:10 -0700 Subject: [PATCH] refactor to share protocol --- client/Connection.ts | 34 ++++++---------------------------- protocol/index.ts | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 28 deletions(-) create mode 100644 protocol/index.ts diff --git a/client/Connection.ts b/client/Connection.ts index ff9a575..7d10b7a 100644 --- a/client/Connection.ts +++ b/client/Connection.ts @@ -1,36 +1,17 @@ +import { + C2SRequestType, + C2SRequestTypes, + S2CRequestType, + S2CRequestTypes, +} from "../protocol"; import Transport from "./Transport"; - -type ObjectValues = T[keyof T]; -const C2SRequestTypes = { - HTTPRequest: 0, - WSOpen: 1, - WSClose: 2, - WSSendText: 3, - WSSendBinary: 4, -} as const; -type C2SRequestType = ObjectValues - -const S2CRequestTypes = { - HTTPResponse: 0, - WSOpen: 1, - WSDataText: 2, - WSDataBinary: 3, -} as const; -type S2CRequestType = ObjectValues - - - - export default class Connection { - - callbacks: Record = {}; counter: number = 0; constructor(public transport: Transport) { - transport.ondata = this.ondata.bind(this); } @@ -61,7 +42,6 @@ export default class Connection { } async send(data: ArrayBuffer | Blob, type: C2SRequestType): Promise { - let requestID = this.counter++; let header = new ArrayBuffer(2 + 1); @@ -80,14 +60,12 @@ export default class Connection { console.log(buf); return requestID; - } httprequest(data: object): Promise { let json = JSON.stringify(data); return new Promise(async (resolve) => { - let id = this.counter; this.callbacks[id] = resolve; await this.send(new Blob([json]), C2SRequestTypes.HTTPRequest); diff --git a/protocol/index.ts b/protocol/index.ts new file mode 100644 index 0000000..a760a98 --- /dev/null +++ b/protocol/index.ts @@ -0,0 +1,17 @@ +export type ObjectValues = T[keyof T]; +export const C2SRequestTypes = { + HTTPRequest: 0, + WSOpen: 1, + WSClose: 2, + WSSendText: 3, + WSSendBinary: 4, +} as const; +export type C2SRequestType = ObjectValues; + +export const S2CRequestTypes = { + HTTPResponse: 0, + WSOpen: 1, + WSDataText: 2, + WSDataBinary: 3, +} as const; +export type S2CRequestType = ObjectValues;