Initial progress

This commit is contained in:
Jack Hadrill
2022-02-01 02:12:49 +00:00
parent 0f2f619e96
commit a93bfc182f
10 changed files with 209 additions and 15 deletions

View File

@@ -1,3 +1,17 @@
export function addNumbers (a: number, b: number): number {
return a + b
import { IMessageEvent } from 'websocket'
import { IncomingPacket } from './structures/server'
export function connect (url: string): void {
const webSocket = new WebSocket(url)
webSocket.binaryType = 'arraybuffer'
webSocket.onopen = onOpen
webSocket.onmessage = onMessage
}
function onOpen (): void {
console.log('Connected!')
}
function onMessage (event: IMessageEvent): void {
console.log(new IncomingPacket(event.data as Buffer))
}

37
src/buffer-reader.ts Normal file
View File

@@ -0,0 +1,37 @@
import { ByteLength } from './common'
export class BufferReader {
private readonly _data: Buffer
private _cursor: number
constructor (data: Buffer = Buffer.from([])) {
this._data = data
this._cursor = 0
}
get cursor (): number {
return this._cursor
}
set cursor (position: number) {
if (position < 0 || position > this._data.length) {
throw RangeError(`Cannot seek to ${this.cursor} of ${this._data.length} bytes.`)
}
this._cursor = position
}
readUInt16 (): number {
this.cursor += ByteLength.UInt16
return this._data.slice(this.cursor - ByteLength.UInt16, this.cursor).readInt16BE()
}
readUInt32 (): number {
this.cursor += ByteLength.UInt32
return this._data.slice(this.cursor - ByteLength.UInt32, this.cursor).readInt32BE()
}
readBuffer (len: number): Buffer {
this.cursor += len
return this._data.slice(this.cursor - len, this.cursor)
}
}

4
src/common.ts Normal file
View File

@@ -0,0 +1,4 @@
export enum ByteLength {
UInt16 = 2,
UInt32 = 4
}

View File

@@ -0,0 +1 @@
export { connect } from './bennc'

16
src/structures/server.ts Normal file
View File

@@ -0,0 +1,16 @@
import { BufferReader } from '../buffer-reader'
export class IncomingPacket extends BufferReader {
messageType: number
senderId: number
length: number
data: Buffer
constructor (data: Buffer) {
super()
this.messageType = this.readUInt16()
this.senderId = this.readUInt32()
this.length = this.readUInt16()
this.data = this.readBuffer(this.length)
}
}