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