]>
Commit | Line | Data |
---|---|---|
2cccf753 SR |
1 | var 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 () { | |
54 | var arr = []; | |
55 | for (var i = 0; i < this.bufferedAmount; i++) { | |
56 | arr[i] = this._send_queue[i]; | |
57 | } | |
58 | ||
59 | this.bufferedAmount = 0; | |
60 | ||
61 | return arr; | |
62 | }, | |
63 | ||
64 | _open: function (data) { | |
65 | this.readyState = FakeWebSocket.OPEN; | |
66 | if (this.onopen) { | |
67 | this.onopen(make_event('open')); | |
68 | } | |
69 | }, | |
70 | ||
71 | _receive_data: function (data) { | |
72 | this.onmessage(make_event("message", { 'data': data })); | |
73 | } | |
74 | }; | |
75 | ||
76 | FakeWebSocket.OPEN = WebSocket.OPEN; | |
77 | FakeWebSocket.CONNECTING = WebSocket.CONNECTING; | |
78 | FakeWebSocket.CLOSING = WebSocket.CLOSING; | |
79 | FakeWebSocket.CLOSED = WebSocket.CLOSED; | |
80 | ||
81 | FakeWebSocket.__is_fake = true; | |
82 | ||
83 | FakeWebSocket.replace = function () { | |
84 | if (!WebSocket.__is_fake) { | |
85 | var real_version = WebSocket; | |
86 | WebSocket = FakeWebSocket; | |
87 | FakeWebSocket.__real_version = real_version; | |
88 | } | |
89 | }; | |
90 | ||
91 | FakeWebSocket.restore = function () { | |
92 | if (WebSocket.__is_fake) { | |
93 | WebSocket = WebSocket.__real_version; | |
94 | } | |
95 | }; | |
96 | })(); |