Skip to content

Instantly share code, notes, and snippets.

@yakovenkodenis
Created November 14, 2022 21:02
Show Gist options
  • Save yakovenkodenis/60a6206dfe702fe99614e4748fcdd83c to your computer and use it in GitHub Desktop.
Save yakovenkodenis/60a6206dfe702fe99614e4748fcdd83c to your computer and use it in GitHub Desktop.
_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',
});
res.end(body);
});
this._server.on('upgrade', (req, socket) => {
this.emit('headers', req);
if (req.headers.upgrade !== 'websocket') {
socket.end('HTTP/1.1 400 Bad Request');
return;
}
const acceptKey = req.headers['sec-websocket-key'];
const acceptValue = this._generateAcceptValue(acceptKey);
const responseHeaders = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${acceptValue}`,
];
socket.write(responseHeaders.concat('\r\n').join('\r\n'));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment