-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
66 lines (50 loc) · 1.19 KB
/
index.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
'use strict';
const WebSocket = require('ws');
const http2 = require('../../source/index.js');
const head = Buffer.from('');
const connect = (url, options) => {
const ws = new WebSocket(null);
ws._isServer = false;
const destroy = async error => {
ws._readyState = WebSocket.CLOSING;
await Promise.resolve();
ws.emit('error', error);
};
(async () => {
try {
const stream = await http2.globalAgent.request(url, options, {
...options,
':method': 'CONNECT',
':protocol': 'websocket',
origin: (new URL(url)).origin
});
stream.once('error', destroy);
stream.once('response', _headers => {
stream.off('error', destroy);
stream.setNoDelay = () => {};
ws.setSocket(stream, head, 100 * 1024 * 1024);
});
} catch (error) {
destroy(error);
}
})();
return ws;
};
const ws = connect('https://localhost:3000', {
// For demo purposes only!
rejectUnauthorized: false
});
ws.once('open', () => {
console.log('CONNECTED!');
ws.send('WebSockets over HTTP/2');
});
ws.once('close', () => {
console.log('DISCONNECTED!');
});
ws.once('message', message => {
console.log(message);
ws.close();
});
ws.once('error', error => {
console.error(error);
});