File: fake.websocket.js

package info (click to toggle)
novnc 1%3A1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,792 kB
  • sloc: python: 202; sh: 164; makefile: 87; perl: 11
file content (87 lines) | stat: -rw-r--r-- 2,293 bytes parent folder | download | duplicates (2)
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
// PhantomJS can't create Event objects directly, so we need to use this
function make_event(name, props) {
    var evt = document.createEvent('Event');
    evt.initEvent(name, true, true);
    if (props) {
        for (var prop in props) {
            evt[prop] = props[prop];
        }
    }
    return evt;
}

export default function FakeWebSocket (uri, protocols) {
    this.url = uri;
    this.binaryType = "arraybuffer";
    this.extensions = "";

    if (!protocols || typeof protocols === 'string') {
        this.protocol = protocols;
    } else {
        this.protocol = protocols[0];
    }

    this._send_queue = new Uint8Array(20000);

    this.readyState = FakeWebSocket.CONNECTING;
    this.bufferedAmount = 0;

    this.__is_fake = true;
};

FakeWebSocket.prototype = {
    close: function (code, reason) {
        this.readyState = FakeWebSocket.CLOSED;
        if (this.onclose) {
            this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true }));
        }
    },

    send: function (data) {
        if (this.protocol == 'base64') {
            data = Base64.decode(data);
        } else {
            data = new Uint8Array(data);
        }
        this._send_queue.set(data, this.bufferedAmount);
        this.bufferedAmount += data.length;
    },

    _get_sent_data: function () {
        var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount);
        this.bufferedAmount = 0;
        return res;
    },

    _open: function (data) {
        this.readyState = FakeWebSocket.OPEN;
        if (this.onopen) {
            this.onopen(make_event('open'));
        }
    },

    _receive_data: function (data) {
        this.onmessage(make_event("message", { 'data': data }));
    }
};

FakeWebSocket.OPEN = WebSocket.OPEN;
FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
FakeWebSocket.CLOSING = WebSocket.CLOSING;
FakeWebSocket.CLOSED = WebSocket.CLOSED;

FakeWebSocket.__is_fake = true;

FakeWebSocket.replace = function () {
    if (!WebSocket.__is_fake) {
        var real_version = WebSocket;
        WebSocket = FakeWebSocket;
        FakeWebSocket.__real_version = real_version;
    }
};

FakeWebSocket.restore = function () {
    if (WebSocket.__is_fake) {
        WebSocket = WebSocket.__real_version;
    }
};