Skip to content

Commit

Permalink
fix(websocket): deprecation warning & 64-bit unsigned int body length (
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev authored Dec 20, 2022
1 parent 0cfe689 commit 01346b5
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 5 deletions.
3 changes: 2 additions & 1 deletion lib/websocket/frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ class WebsocketFrameSend {
if (payloadLength === 126) {
new DataView(buffer.buffer).setUint16(2, bodyLength)
} else if (payloadLength === 127) {
// TODO: optimize this once tests are added for payloads >= 2^16 bytes
// Clear extended payload length
buffer[2] = buffer[3] = 0
buffer.writeUIntBE(bodyLength, 4, 6)
}

Expand Down
6 changes: 3 additions & 3 deletions lib/websocket/receiver.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,10 @@ class ByteParser extends Writable {
}

const buffer = this.consume(8)
const upper = buffer.readUInt32BE(0)
const lower = buffer.readUInt32BE(4)

// TODO: optimize this
// TODO: this likely doesn't work because it returns a bigint
this.#info.payloadLength = buffer.readBigUint64BE(0)
this.#info.payloadLength = (upper << 8) + lower
this.#state = parserStates.READ_DATA
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) {
Expand Down
9 changes: 8 additions & 1 deletion lib/websocket/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,14 @@ class WebSocket extends EventTarget {
// by the length of data’s buffer in bytes.

const ab = new ArrayBuffer(data.byteLength)
new data.constructor(ab).set(data)

if (Buffer.isBuffer(data)) {
// new Buffer signature is deprecated
Buffer.from(ab).set(data)
} else {
new data.constructor(ab).set(data)
}

const value = Buffer.from(ab)

const frame = new WebsocketFrameSend(value)
Expand Down
35 changes: 35 additions & 0 deletions test/websocket/send.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict'

const { test } = require('tap')
const { WebSocketServer } = require('ws')
const { Blob } = require('buffer')
const { WebSocket } = require('../..')

test('Sending > 2^16 bytes', (t) => {
t.plan(3)

const server = new WebSocketServer({ port: 0 })

server.on('connection', (ws) => {
ws.on('message', (m, isBinary) => {
ws.send(m, { binary: isBinary })
})
})

const payload = Buffer.allocUnsafe(2 ** 16).fill('Hello')

const ws = new WebSocket(`ws://localhost:${server.address().port}`)

ws.addEventListener('open', () => {
ws.send(payload)
})

ws.addEventListener('message', async ({ data }) => {
t.type(data, Blob)
t.equal(data.size, payload.length)
t.same(Buffer.from(await data.arrayBuffer()), payload)

ws.close()
server.close()
})
})

0 comments on commit 01346b5

Please sign in to comment.