Skip to content

Instantly share code, notes, and snippets.

View yakovenkodenis's full-sized avatar
:octocat:

Denis Yakovenko yakovenkodenis

:octocat:
  • Ukraine, Kharkiv
View GitHub Profile
_init() {
if (this._server) throw new Error('Server already initialized');
this._server = http.createServer((req, res) => {
const UPGRADE_REQUIRED = 426;
const body = http.STATUS_CODES[UPGRADE_REQUIRED];
res.writeHead(UPGRADE_REQUIRED, {
'Content-Type': 'text/plain',
'Upgrade': 'WebSocket',
});
_init() {
if (this._server) throw new Error('Server already initialized');
this._server = http.createServer((req, res) => {
const UPGRADE_REQUIRED = 426;
const body = http.STATUS_CODES[UPGRADE_REQUIRED];
res.writeHead(UPGRADE_REQUIRED, {
'Content-Type': 'text/plain',
'Upgrade': 'WebSocket',
});
_generateAcceptValue(acceptKey) {
return crypto
.createHash('sha1')
.update(acceptKey + this.GUID, 'binary')
.digest('base64');
}
listen(callback) {
this._server.listen(this.port, callback);
}
const PORT = 4000.
const server = new WebSocketServer({ port: PORT });
server.on('headers', ({ headers }) => console.log(headers));
server.listen(() => {
console.log(`WebSocket server listening on port ${PORT}`);
});
Opcode value Meaning
0x00 Denotes that this frame continues the payload from the previous frame
0x01 Denotes a text frame
0x02 Denotes a binary frame
0x08 Denotes that the client wants to close the connection
0x09, 0x0a ping and pong frames - a heartbeat mechanism for ensuring the connection is still alive
0x03 - 0x07, 0x0b - 0x0f Reserved for future use
@yakovenkodenis
yakovenkodenis / ws.js
Created November 20, 2022 18:48
frame first byte
parseFrame(buffer) {
const firstByte = buffer.readUInt8(0);
const opCode = firstByte & 0b00001111; // get last 4 bits of a byte
if (opCode === this.OPCODES.close) {
this.emit('close');
return null;
} else if (opCode !== this.OPCODES.text) {
return;
}
this._server.on('upgrade', (req, socket) => {
// ...upgrade request code...
this.on('close', () => {
console.log('closing....', socket);
socket.destroy();
});
});
parseFrame(buffer) {
// ... first byte processing ...
const secondByte = buffer.readUInt8(1);
let offset = 2;
let payloadLength = secondByte & 0b01111111; // get last 7 bits of a second byte
if (payloadLength === 126) {
offset += 2;
parseFrame(buffer) {
// ... first and second byte processing ...
const isMasked = Boolean((secondByte >>> 7) & 0b00000001); // get first bit of a second byte
if (isMasked) {
const maskingKey = buffer.readUInt32BE(offset); // read 4-byte (32-bit) masking key
offset += 4;
const payload = buffer.subarray(offset);
const result = this._unmask(payload, maskingKey);