Skip to content

Instantly share code, notes, and snippets.

@Srushtika
Last active October 13, 2019 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Srushtika/79a21b90167874278410e80d63657504 to your computer and use it in GitHub Desktop.
Save Srushtika/79a21b90167874278410e80d63657504 to your computer and use it in GitHub Desktop.
WebSockets server tutorial
function parseMessage (buffer) {
const firstByte = buffer.readUInt8(0);
const isFinalFrame = Boolean((firstByte >>> 7) & 0×1);
const [reserved1, reserved2, reserved3] = [ Boolean((firstByte >>> 6) & 0×1), Boolean((firstByte >>> 5) & 0×1), Boolean((firstByte >>> 4) & 0×1) ];
const opCode = firstByte & 0xF;
// We can return null to signify that this is a connection termination frame
if (opCode === 0×8)
return null;
// We only care about text frames from this point onward
if (opCode !== 0×1)
return;
const secondByte = buffer.readUInt8(1);
const isMasked = Boolean((secondByte >>> 7) & 0×1);
// Keep track of our current position as we advance through the buffer
let currentOffset = 2; let payloadLength = secondByte & 0×7F;
if (payloadLength > 125) {
if (payloadLength === 126) {
payloadLength = buffer.readUInt16BE(currentOffset);
currentOffset += 2;
} else {
// 127
// If this has a value, the frame size is ridiculously huge!
const leftPart = buffer.readUInt32BE(currentOffset);
const rightPart = buffer.readUInt32BE(currentOffset += 4);
// Honestly, if the frame length requires 64 bits, you're probably doing it wrong.
// In Node.js you'll require the BigInt type, or a special library to handle this.
throw new Error('Large payloads not currently implemented');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment