forked from novnc/noVNC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfake.websocket.js
88 lines (73 loc) · 2.32 KB
/
fake.websocket.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
import Base64 from '../core/base64.js';
export default class FakeWebSocket {
constructor(uri, protocols) {
this.url = uri;
this.binaryType = "arraybuffer";
this.extensions = "";
this.onerror = null;
this.onmessage = null;
this.onopen = null;
if (!protocols || typeof protocols === 'string') {
this.protocol = protocols;
} else {
this.protocol = protocols[0];
}
this._sendQueue = new Uint8Array(20000);
this.readyState = FakeWebSocket.CONNECTING;
this.bufferedAmount = 0;
this._isFake = true;
}
close(code, reason) {
this.readyState = FakeWebSocket.CLOSED;
if (this.onclose) {
this.onclose(new CloseEvent("close", { 'code': code, 'reason': reason, 'wasClean': true }));
}
}
send(data) {
if (this.protocol == 'base64') {
data = Base64.decode(data);
} else {
data = new Uint8Array(data);
}
this._sendQueue.set(data, this.bufferedAmount);
this.bufferedAmount += data.length;
}
_getSentData() {
const res = new Uint8Array(this._sendQueue.buffer, 0, this.bufferedAmount);
this.bufferedAmount = 0;
return res;
}
_open() {
this.readyState = FakeWebSocket.OPEN;
if (this.onopen) {
this.onopen(new Event('open'));
}
}
_receiveData(data) {
// Break apart the data to expose bugs where we assume data is
// neatly packaged
for (let i = 0;i < data.length;i++) {
let buf = data.subarray(i, i+1);
this.onmessage(new MessageEvent("message", { 'data': buf }));
}
}
}
FakeWebSocket.OPEN = WebSocket.OPEN;
FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
FakeWebSocket.CLOSING = WebSocket.CLOSING;
FakeWebSocket.CLOSED = WebSocket.CLOSED;
FakeWebSocket._isFake = true;
FakeWebSocket.replace = () => {
if (!WebSocket._isFake) {
const realVersion = WebSocket;
// eslint-disable-next-line no-global-assign
WebSocket = FakeWebSocket;
FakeWebSocket._realVersion = realVersion;
}
};
FakeWebSocket.restore = () => {
if (WebSocket._isFake) {
// eslint-disable-next-line no-global-assign
WebSocket = WebSocket._realVersion;
}
};