Skip to content

Commit

Permalink
Additional WebSocket send tests to cover all payload size categories (#…
Browse files Browse the repository at this point in the history
…2149)

* Fixed bug in 16-bit frame length when buffer is a subarray

I was just bitten by this issue. Because buffer could be a subarray, the `byteOffset` and `byteLength` arguments to `new DataView()` are required, otherwise the length value may be written at the wrong offset.

Alternatively, it looks like it would be simpler (and it also works) to replace the patched line with `buffer.writeUInt16BE(bodyLength, 2)`.

* Switched 16-bit length-writing fix to use Buffer.writeUInt16 instead of DataView.setUint16, and added a test for the fix

* Added WebSocket send tests for the two previously-untested payload size categories
  • Loading branch information
jawj committed Jun 7, 2023
1 parent a3e0fdc commit 2032e89
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion test/websocket/send.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ const { WebSocketServer } = require('ws')
const { Blob } = require('buffer')
const { WebSocket } = require('../..')

test('Sending > 2^16 bytes', (t) => {
// the following three tests exercise different code paths because of the three
// different ways a payload length may be specified in a WebSocket frame
// (https://datatracker.ietf.org/doc/html/rfc6455#section-5.2)

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

const server = new WebSocketServer({ port: 0 })
Expand Down Expand Up @@ -34,6 +38,64 @@ test('Sending > 2^16 bytes', (t) => {
})
})

test('Sending >= 126, < 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(126).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()
})
})

test('Sending < 126 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(125).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()
})
})

test('Sending data after close', (t) => {
t.plan(2)

Expand Down

0 comments on commit 2032e89

Please sign in to comment.