Skip to content

Commit 4608ef1

Browse files
authored
fix sending ping with no payload (#4329)
1 parent 0016bdd commit 4608ef1

2 files changed

Lines changed: 28 additions & 7 deletions

File tree

lib/web/websocket/websocket.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -594,10 +594,12 @@ class WebSocket extends EventTarget {
594594
* @param {Buffer|undefined} buffer
595595
*/
596596
static ping (ws, buffer) {
597-
if (!Buffer.isBuffer(buffer)) {
597+
if (Buffer.isBuffer(buffer)) {
598+
if (buffer.length > 125) {
599+
throw new TypeError('A PING frame cannot have a body larger than 125 bytes.')
600+
}
601+
} else if (buffer !== undefined) {
598602
throw new TypeError('Expected buffer payload')
599-
} else if (buffer.length > 125) {
600-
throw new TypeError('A PING frame cannot have a body larger than 125 bytes.')
601603
}
602604

603605
// An endpoint MAY send a Ping frame any time after the connection is

test/websocket/ping-util.js

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,7 @@ test('ping', async (t) => {
1818
})
1919

2020
const ws = new WebSocket(`ws://localhost:${wss.address().port}`)
21-
22-
ws.addEventListener('open', () => {
23-
ping(ws, pingBody)
24-
})
21+
ws.onopen = () => ping(ws, pingBody)
2522

2623
t.after(() => {
2724
ws.close()
@@ -54,3 +51,25 @@ test('attempting to send invalid ping body', async (t) => {
5451

5552
await completed
5653
})
54+
55+
test('ping with no payload', async (t) => {
56+
const { completed, deepStrictEqual } = tspl(t, { plan: 1 })
57+
58+
const wss = new WebSocketServer({ port: 0 })
59+
60+
wss.on('connection', (ws) => {
61+
ws.on('ping', (b) => {
62+
deepStrictEqual(b, Buffer.alloc(0))
63+
})
64+
})
65+
66+
const ws = new WebSocket(`ws://localhost:${wss.address().port}`)
67+
ws.onopen = () => ping(ws)
68+
69+
t.after(() => {
70+
ws.close()
71+
wss.close()
72+
})
73+
74+
await completed
75+
})

0 commit comments

Comments
 (0)