]> git.proxmox.com Git - mirror_novnc.git/blob - tests/fake.websocket.js
Merge branch 'api' of https://github.com/CendioOssman/noVNC
[mirror_novnc.git] / tests / fake.websocket.js
1 // PhantomJS can't create Event objects directly, so we need to use this
2 function make_event(name, props) {
3 var evt = document.createEvent('Event');
4 evt.initEvent(name, true, true);
5 if (props) {
6 for (var prop in props) {
7 evt[prop] = props[prop];
8 }
9 }
10 return evt;
11 }
12
13 export default function FakeWebSocket (uri, protocols) {
14 this.url = uri;
15 this.binaryType = "arraybuffer";
16 this.extensions = "";
17
18 if (!protocols || typeof protocols === 'string') {
19 this.protocol = protocols;
20 } else {
21 this.protocol = protocols[0];
22 }
23
24 this._send_queue = new Uint8Array(20000);
25
26 this.readyState = FakeWebSocket.CONNECTING;
27 this.bufferedAmount = 0;
28
29 this.__is_fake = true;
30 };
31
32 FakeWebSocket.prototype = {
33 close: function (code, reason) {
34 this.readyState = FakeWebSocket.CLOSED;
35 if (this.onclose) {
36 this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true }));
37 }
38 },
39
40 send: function (data) {
41 if (this.protocol == 'base64') {
42 data = Base64.decode(data);
43 } else {
44 data = new Uint8Array(data);
45 }
46 this._send_queue.set(data, this.bufferedAmount);
47 this.bufferedAmount += data.length;
48 },
49
50 _get_sent_data: function () {
51 var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount);
52 this.bufferedAmount = 0;
53 return res;
54 },
55
56 _open: function (data) {
57 this.readyState = FakeWebSocket.OPEN;
58 if (this.onopen) {
59 this.onopen(make_event('open'));
60 }
61 },
62
63 _receive_data: function (data) {
64 this.onmessage(make_event("message", { 'data': data }));
65 }
66 };
67
68 FakeWebSocket.OPEN = WebSocket.OPEN;
69 FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
70 FakeWebSocket.CLOSING = WebSocket.CLOSING;
71 FakeWebSocket.CLOSED = WebSocket.CLOSED;
72
73 FakeWebSocket.__is_fake = true;
74
75 FakeWebSocket.replace = function () {
76 if (!WebSocket.__is_fake) {
77 var real_version = WebSocket;
78 WebSocket = FakeWebSocket;
79 FakeWebSocket.__real_version = real_version;
80 }
81 };
82
83 FakeWebSocket.restore = function () {
84 if (WebSocket.__is_fake) {
85 WebSocket = WebSocket.__real_version;
86 }
87 };