-
Notifications
You must be signed in to change notification settings - Fork 570
/
websocket-send-buffer.mjs
87 lines (76 loc) · 1.89 KB
/
websocket-send-buffer.mjs
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
// --------------------SERVER--------------------
// -> /server/simple.mjs
// ----------------------------------------------
import { WebSocket as WsWebSocket } from 'ws'
import { WebSocket as UndiciWebSocket } from '../../index.js'
import { randomBytes } from 'node:crypto'
import { bench, run, group } from 'mitata'
const __GLOBAL_WEBSOCKET__ = true
const __BINARY_SIZE__ = 1024 * 256
let GlobalWebSocket = null
if (__GLOBAL_WEBSOCKET__ && typeof globalThis.WebSocket === 'function') {
GlobalWebSocket = globalThis.WebSocket
}
const binary = randomBytes(__BINARY_SIZE__)
const url = 'http://localhost:5001'
const connections = []
group('send', () => {
{
const ws = new WsWebSocket(url)
let _resolve
ws.addEventListener('message', () => {
_resolve()
})
bench('ws', () => {
return new Promise((resolve, reject) => {
ws.send(binary)
_resolve = resolve
})
})
connections.push(ws)
}
{
const ws = new UndiciWebSocket(url)
let _resolve
ws.addEventListener('message', () => {
_resolve()
})
bench('undici', () => {
return new Promise((resolve, reject) => {
ws.send(binary)
_resolve = resolve
})
})
connections.push(ws)
}
if (typeof GlobalWebSocket === 'function') {
const ws = new GlobalWebSocket(url)
let _resolve
ws.addEventListener('message', () => {
_resolve()
})
bench('undici - global', () => {
return new Promise((resolve, reject) => {
ws.send(binary)
_resolve = resolve
})
})
connections.push(ws)
}
})
for (const ws of connections) {
// for fairness
ws.binaryType = 'arraybuffer'
await new Promise((resolve, reject) => {
ws.addEventListener('open', () => {
resolve()
})
ws.addEventListener('error', (err) => {
reject(err)
})
})
}
await run()
for (const ws of connections) {
ws.close()
}