diff --git a/lib/web/websocket/websocket.js b/lib/web/websocket/websocket.js index f3add9e6e9a..05fac013af7 100644 --- a/lib/web/websocket/websocket.js +++ b/lib/web/websocket/websocket.js @@ -594,10 +594,12 @@ class WebSocket extends EventTarget { * @param {Buffer|undefined} buffer */ static ping (ws, buffer) { - if (!Buffer.isBuffer(buffer)) { + if (Buffer.isBuffer(buffer)) { + if (buffer.length > 125) { + throw new TypeError('A PING frame cannot have a body larger than 125 bytes.') + } + } else if (buffer !== undefined) { throw new TypeError('Expected buffer payload') - } else if (buffer.length > 125) { - throw new TypeError('A PING frame cannot have a body larger than 125 bytes.') } // An endpoint MAY send a Ping frame any time after the connection is diff --git a/test/websocket/ping-util.js b/test/websocket/ping-util.js index b4ad9f57553..176d602aaec 100644 --- a/test/websocket/ping-util.js +++ b/test/websocket/ping-util.js @@ -18,10 +18,7 @@ test('ping', async (t) => { }) const ws = new WebSocket(`ws://localhost:${wss.address().port}`) - - ws.addEventListener('open', () => { - ping(ws, pingBody) - }) + ws.onopen = () => ping(ws, pingBody) t.after(() => { ws.close() @@ -54,3 +51,25 @@ test('attempting to send invalid ping body', async (t) => { await completed }) + +test('ping with no payload', async (t) => { + const { completed, deepStrictEqual } = tspl(t, { plan: 1 }) + + const wss = new WebSocketServer({ port: 0 }) + + wss.on('connection', (ws) => { + ws.on('ping', (b) => { + deepStrictEqual(b, Buffer.alloc(0)) + }) + }) + + const ws = new WebSocket(`ws://localhost:${wss.address().port}`) + ws.onopen = () => ping(ws) + + t.after(() => { + ws.close() + wss.close() + }) + + await completed +})