]> git.proxmox.com Git - mirror_novnc.git/blame - tests/fake.websocket.js
noVNC 1.0.0
[mirror_novnc.git] / tests / fake.websocket.js
CommitLineData
dfae3209
SR
1// PhantomJS can't create Event objects directly, so we need to use this
2function 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];
2cccf753 8 }
2cccf753 9 }
dfae3209
SR
10 return evt;
11}
2cccf753 12
dfae3209
SR
13export default function FakeWebSocket (uri, protocols) {
14 this.url = uri;
15 this.binaryType = "arraybuffer";
16 this.extensions = "";
2cccf753 17
dfae3209
SR
18 if (!protocols || typeof protocols === 'string') {
19 this.protocol = protocols;
20 } else {
21 this.protocol = protocols[0];
22 }
2cccf753 23
dfae3209 24 this._send_queue = new Uint8Array(20000);
2cccf753 25
dfae3209
SR
26 this.readyState = FakeWebSocket.CONNECTING;
27 this.bufferedAmount = 0;
2cccf753 28
dfae3209
SR
29 this.__is_fake = true;
30};
2cccf753 31
dfae3209
SR
32FakeWebSocket.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 },
2cccf753 39
dfae3209
SR
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 },
2cccf753 49
dfae3209
SR
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 },
2cccf753 55
dfae3209
SR
56 _open: function (data) {
57 this.readyState = FakeWebSocket.OPEN;
58 if (this.onopen) {
59 this.onopen(make_event('open'));
2cccf753 60 }
dfae3209 61 },
2cccf753 62
dfae3209
SR
63 _receive_data: function (data) {
64 this.onmessage(make_event("message", { 'data': data }));
65 }
66};
2cccf753 67
dfae3209
SR
68FakeWebSocket.OPEN = WebSocket.OPEN;
69FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
70FakeWebSocket.CLOSING = WebSocket.CLOSING;
71FakeWebSocket.CLOSED = WebSocket.CLOSED;
2cccf753 72
dfae3209 73FakeWebSocket.__is_fake = true;
2cccf753 74
dfae3209
SR
75FakeWebSocket.replace = function () {
76 if (!WebSocket.__is_fake) {
77 var real_version = WebSocket;
78 WebSocket = FakeWebSocket;
79 FakeWebSocket.__real_version = real_version;
80 }
81};
82
83FakeWebSocket.restore = function () {
84 if (WebSocket.__is_fake) {
85 WebSocket = WebSocket.__real_version;
86 }
87};