cj-2307
cj-2307

Reputation: 311

Invalid WebSocket frame: MASK must be clear

I'm using the ws package to connect to the poloniex web socket, using the following code:

const WS = require('ws');

const ws = new WS('wss://api2.poloniex.com');
ws.on('open', () => {
    ws.send(JSON.stringify({
        command: 'subscribe',
        channel: 'USDT_BTC'
    }));
});
ws.on('message', (msg) => {
    console.log(JSON.parse(msg));
    ws.close(1000);
});
ws.on('close', (code) => {
    console.log(`closing with code ${code}`);
});
ws.on('error', (error) => {
    console.error(error);
});

Hovewer I get the following output:

RangeError: Invalid WebSocket frame: MASK must be clear
    at Receiver.getInfo (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:299:14)
    at Receiver.startLoop (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:136:22)
    at Receiver._write (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:83:10)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at Receiver.Writable.write (internal/streams/writable.js:303:10)
    at TLSSocket.socketOnData (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/websocket.js:1116:35)
    at TLSSocket.emit (events.js:400:28)
    at addChunk (internal/streams/readable.js:293:12)
    at readableAddChunk (internal/streams/readable.js:267:9)
    at TLSSocket.Readable.push (internal/streams/readable.js:206:10) {
  code: 'WS_ERR_UNEXPECTED_MASK',
  [Symbol(status-code)]: 1002
}
closing with code 1006

Does any one know what this error means? I tried a similar code with similar servers and I don't get any error. Also, if I don't send any code to the function ws.close(), I don't get any error. Does any one knows why this happens? What

Upvotes: 2

Views: 1547

Answers (1)

GhostRavenstorm
GhostRavenstorm

Reputation: 754

Just learned this trying to do my own WebSocket implemetation in C#. What the error means by "MASK must be clear" is that the data isn't expected to be masked; meaning omit the XOR key and don't encode the payload.

Byte exmaple of a frame sending "hi" encoded:

     Mask bit set and 7-bit payload length
     vv
{81, 82, 97, 34, 89, 6A, FF, 5D}
         ^^^^^^^^^^^^^^  ^^^^^^
         Mask Key        Encoded Payload

Byte exmaple of a frame sending "hi" unencoded:
Note there is no mask key.

     Mask bit not set and 7-bit payload length
     v
{81, 2, 68, 69}
        ^^^^^^
        Raw Payload

Since you seem to be working with a WebSocket library in JS, I'd look to see if there's a parameter you must set that is encoding what your ws.send() is doing.

Upvotes: 1

Related Questions