forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple.js
100 lines (78 loc) · 2.24 KB
/
simple.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const common = require('../common.js');
const crypto = require('crypto');
const http = require('http');
const { WebSocket } = require('undici');
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const configs = {
size: [64, 16 * 1024, 128 * 1024, 1024 * 1024],
useBinary: ['true', 'false'],
roundtrips: [5000, 1000, 100, 1],
};
const bench = common.createBenchmark(main, configs);
function createFrame(data, opcode) {
let infoLength = 2;
let payloadLength = data.length;
if (payloadLength >= 65536) {
infoLength += 8;
payloadLength = 127;
} else if (payloadLength > 125) {
infoLength += 2;
payloadLength = 126;
}
const info = Buffer.alloc(infoLength);
info[0] = opcode | 0x80;
info[1] = payloadLength;
if (payloadLength === 126) {
info.writeUInt16BE(data.length, 2);
} else if (payloadLength === 127) {
info[2] = info[3] = 0;
info.writeUIntBE(data.length, 4, 6);
}
return Buffer.concat([info, data]);
}
function main(conf) {
const frame = createFrame(Buffer.alloc(conf.size).fill('.'), 1);
const server = http.createServer();
server.on('upgrade', (req, socket) => {
const key = crypto
.createHash('sha1')
.update(req.headers['sec-websocket-key'] + GUID)
.digest('base64');
let bytesReceived = 0;
let roundtrip = 0;
socket.on('data', function onData(chunk) {
bytesReceived += chunk.length;
if (bytesReceived === frame.length + 4) { // +4 for the mask.
// Message completely received.
bytesReceived = 0;
if (++roundtrip === conf.roundtrips) {
socket.removeListener('data', onData);
socket.resume();
socket.end();
server.close();
bench.end(conf.roundtrips);
} else {
socket.write(frame);
}
}
});
socket.write(
[
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${key}`,
'\r\n',
].join('\r\n'),
);
socket.write(frame);
});
server.listen(8080, () => {
const ws = new WebSocket('ws://localhost:8080');
ws.addEventListener('message', (event) => {
ws.send(event.data);
});
});
bench.start();
}