Skip to content

Instantly share code, notes, and snippets.

@lpinca
Created June 10, 2021 18:33
Show Gist options
  • Save lpinca/be56024eca9d4a1efc701364e6ec9513 to your computer and use it in GitHub Desktop.
Save lpinca/be56024eca9d4a1efc701364e6ec9513 to your computer and use it in GitHub Desktop.
websockets/ws PR 1899 discussion
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const stream = require('stream');
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const data = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
(function () {
const data = new Uint8Array(1024);
const ws = new WebSocket('ws://localhost:8080');
let sendInterval = setInterval(function () {
if (ws.readyState === WebSocket.OPEN) ws.send(data);
});
let logInterval = setInterval(function () {
console.log((ws.bufferedAmount / 1024 / 1024).toFixed(2), 'MiB');
}, 1000);
ws.onopen = function () {
console.log('open');
};
ws.onclose = function (evt) {
console.log(evt.code);
clearInterval(sendInterval);
clearInterval(logInterval);
};
})();
</script>
</body>
</html>`;
const server = http.createServer();
const fileStream = fs.createWriteStream('data.bin');
fileStream.on('close', function () {
server.close();
});
const transform = new stream.Transform({
transform(chunk, encoding, callback) {
setTimeout(callback, 1000, null, chunk);
}
});
server.on('request', function (request, response) {
response.setHeader('Content-Type', 'text/html');
response.end(data);
});
server.on('upgrade', function (request, socket) {
const key = crypto
.createHash('sha1')
.update(request.headers['sec-websocket-key'] + GUID)
.digest('base64');
socket.on('error', console.error);
socket.pipe(transform).pipe(fileStream);
socket.write(
[
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${key}`,
'\r\n'
].join('\r\n')
);
process.once('SIGINT', function () {
console.log('Sending the close frame');
socket.write(Buffer.from([0x88, 0x00]));
socket.end();
});
});
server.listen(8080, function () {
console.log('Listening on *:8080');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment