]> git.proxmox.com Git - mirror_novnc.git/blame - core/websock.js
Switch to URL for connect()
[mirror_novnc.git] / core / websock.js
CommitLineData
72f1348b
JM
1/*
2 * Websock: high-performance binary WebSockets
d58f8b51 3 * Copyright (C) 2012 Joel Martin
1d728ace 4 * Licensed under MPL 2.0 (see LICENSE.txt)
72f1348b 5 *
d2467189
PO
6 * Websock is similar to the standard WebSocket object but with extra
7 * buffer handling.
72f1348b
JM
8 *
9 * Websock has built-in receive queue buffering; the message event
10 * does not contain actual data but is simply a notification that
11 * there is new data available. Several rQ* methods are available to
12 * read binary data off of the receive queue.
13 */
14
6d6f0db0 15import * as Log from './util/logging.js';
ae510306 16
2cccf753 17/*jslint browser: true, bitwise: true */
38781d93 18/*global Util*/
ff4bfcb7 19
3ae0bb09 20export default function Websock() {
2cccf753
SR
21 "use strict";
22
23 this._websocket = null; // WebSocket object
38781d93 24
2cccf753 25 this._rQi = 0; // Receive queue index
38781d93
SR
26 this._rQlen = 0; // Next write position in the receive queue
27 this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
28 this._rQmax = this._rQbufferSize / 8;
38781d93
SR
29 // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
30 this._rQ = null; // Receive queue
2cccf753 31
9ff86fb7
SR
32 this._sQbufferSize = 1024 * 10; // 10 KiB
33 // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
34 this._sQlen = 0;
35 this._sQ = null; // Send queue
36
2cccf753
SR
37 this._eventHandlers = {
38 'message': function () {},
39 'open': function () {},
40 'close': function () {},
41 'error': function () {}
42 };
ae510306 43};
72f1348b 44
6d6f0db0
SR
45// this has performance issues in some versions Chromium, and
46// doesn't gain a tremendous amount of performance increase in Firefox
47// at the moment. It may be valuable to turn it on in the future.
48var ENABLE_COPYWITHIN = false;
49
50var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
51
52var typedArrayToString = (function () {
53 // This is only for PhantomJS, which doesn't like apply-ing
54 // with Typed Arrays
55 try {
56 var arr = new Uint8Array([1, 2, 3]);
57 String.fromCharCode.apply(null, arr);
58 return function (a) { return String.fromCharCode.apply(null, a); };
59 } catch (ex) {
60 return function (a) {
61 return String.fromCharCode.apply(
62 null, Array.prototype.slice.call(a));
63 };
64 }
65})();
40037b6a 66
6d6f0db0
SR
67Websock.prototype = {
68 // Getters and Setters
69 get_sQ: function () {
70 return this._sQ;
71 },
72
73 get_rQ: function () {
74 return this._rQ;
75 },
76
77 get_rQi: function () {
78 return this._rQi;
79 },
80
81 set_rQi: function (val) {
82 this._rQi = val;
83 },
84
85 // Receive Queue
86 rQlen: function () {
87 return this._rQlen - this._rQi;
88 },
89
90 rQpeek8: function () {
91 return this._rQ[this._rQi];
92 },
93
94 rQshift8: function () {
95 return this._rQ[this._rQi++];
96 },
97
98 rQskip8: function () {
99 this._rQi++;
100 },
101
102 rQskipBytes: function (num) {
103 this._rQi += num;
104 },
105
106 // TODO(directxman12): test performance with these vs a DataView
107 rQshift16: function () {
108 return (this._rQ[this._rQi++] << 8) +
109 this._rQ[this._rQi++];
110 },
111
112 rQshift32: function () {
113 return (this._rQ[this._rQi++] << 24) +
114 (this._rQ[this._rQi++] << 16) +
115 (this._rQ[this._rQi++] << 8) +
116 this._rQ[this._rQi++];
117 },
118
119 rQshiftStr: function (len) {
120 if (typeof(len) === 'undefined') { len = this.rQlen(); }
121 var arr = new Uint8Array(this._rQ.buffer, this._rQi, len);
122 this._rQi += len;
123 return typedArrayToString(arr);
124 },
125
126 rQshiftBytes: function (len) {
127 if (typeof(len) === 'undefined') { len = this.rQlen(); }
128 this._rQi += len;
129 return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
130 },
131
132 rQshiftTo: function (target, len) {
133 if (len === undefined) { len = this.rQlen(); }
134 // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
135 target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
136 this._rQi += len;
137 },
138
139 rQwhole: function () {
140 return new Uint8Array(this._rQ.buffer, 0, this._rQlen);
141 },
142
143 rQslice: function (start, end) {
144 if (end) {
145 return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
146 } else {
147 return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start);
38781d93 148 }
6d6f0db0
SR
149 },
150
151 // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
152 // to be available in the receive queue. Return true if we need to
153 // wait (and possibly print a debug message), otherwise false.
154 rQwait: function (msg, num, goback) {
155 var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
156 if (rQlen < num) {
157 if (goback) {
158 if (this._rQi < goback) {
159 throw new Error("rQwait cannot backup " + goback + " bytes");
2cccf753 160 }
6d6f0db0 161 this._rQi -= goback;
2cccf753 162 }
6d6f0db0
SR
163 return true; // true means need more data
164 }
165 return false;
166 },
72f1348b 167
6d6f0db0 168 // Send Queue
72f1348b 169
6d6f0db0
SR
170 flush: function () {
171 if (this._websocket.bufferedAmount !== 0) {
172 Log.Debug("bufferedAmount: " + this._websocket.bufferedAmount);
173 }
72f1348b 174
6d6f0db0
SR
175 if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
176 this._websocket.send(this._encode_message());
177 this._sQlen = 0;
178 }
179 },
180
181 send: function (arr) {
182 this._sQ.set(arr, this._sQlen);
183 this._sQlen += arr.length;
184 this.flush();
185 },
186
187 send_string: function (str) {
188 this.send(str.split('').map(function (chr) {
189 return chr.charCodeAt(0);
190 }));
191 },
192
193 // Event Handlers
194 off: function (evt) {
195 this._eventHandlers[evt] = function () {};
196 },
197
198 on: function (evt, handler) {
199 this._eventHandlers[evt] = handler;
200 },
201
202 _allocate_buffers: function () {
203 this._rQ = new Uint8Array(this._rQbufferSize);
204 this._sQ = new Uint8Array(this._sQbufferSize);
205 },
206
207 init: function () {
208 this._allocate_buffers();
209 this._rQi = 0;
210 this._websocket = null;
211 },
212
213 open: function (uri, protocols) {
214 var ws_schema = uri.match(/^([a-z]+):\/\//)[1];
215 this.init();
216
217 this._websocket = new WebSocket(uri, protocols);
218 this._websocket.binaryType = 'arraybuffer';
219
220 this._websocket.onmessage = this._recv_message.bind(this);
221 this._websocket.onopen = (function () {
222 Log.Debug('>> WebSock.onopen');
223 if (this._websocket.protocol) {
224 Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
2cccf753 225 }
2cccf753 226
6d6f0db0
SR
227 this._eventHandlers.open();
228 Log.Debug("<< WebSock.onopen");
229 }).bind(this);
230 this._websocket.onclose = (function (e) {
231 Log.Debug(">> WebSock.onclose");
232 this._eventHandlers.close(e);
233 Log.Debug("<< WebSock.onclose");
234 }).bind(this);
235 this._websocket.onerror = (function (e) {
236 Log.Debug(">> WebSock.onerror: " + e);
237 this._eventHandlers.error(e);
238 Log.Debug("<< WebSock.onerror: " + e);
239 }).bind(this);
240 },
241
242 close: function () {
243 if (this._websocket) {
244 if ((this._websocket.readyState === WebSocket.OPEN) ||
245 (this._websocket.readyState === WebSocket.CONNECTING)) {
246 Log.Info("Closing WebSocket connection");
247 this._websocket.close();
fcff386b 248 }
6d6f0db0
SR
249
250 this._websocket.onmessage = function (e) { return; };
251 }
252 },
253
254 // private methods
255 _encode_message: function () {
256 // Put in a binary arraybuffer
257 // according to the spec, you can send ArrayBufferViews with the send method
258 return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
259 },
260
261 _expand_compact_rQ: function (min_fit) {
262 var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2;
263 if (resizeNeeded) {
264 if (!min_fit) {
265 // just double the size if we need to do compaction
266 this._rQbufferSize *= 2;
267 } else {
268 // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8
269 this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8;
40037b6a 270 }
6d6f0db0 271 }
40037b6a 272
6d6f0db0
SR
273 // we don't want to grow unboundedly
274 if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
275 this._rQbufferSize = MAX_RQ_GROW_SIZE;
276 if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) {
277 throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
40037b6a 278 }
6d6f0db0 279 }
40037b6a 280
6d6f0db0
SR
281 if (resizeNeeded) {
282 var old_rQbuffer = this._rQ.buffer;
283 this._rQmax = this._rQbufferSize / 8;
284 this._rQ = new Uint8Array(this._rQbufferSize);
285 this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
286 } else {
287 if (ENABLE_COPYWITHIN) {
288 this._rQ.copyWithin(0, this._rQi);
40037b6a 289 } else {
6d6f0db0 290 this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
40037b6a 291 }
6d6f0db0 292 }
40037b6a 293
6d6f0db0
SR
294 this._rQlen = this._rQlen - this._rQi;
295 this._rQi = 0;
296 },
40037b6a 297
6d6f0db0
SR
298 _decode_message: function (data) {
299 // push arraybuffer values onto the end
300 var u8 = new Uint8Array(data);
301 if (u8.length > this._rQbufferSize - this._rQlen) {
302 this._expand_compact_rQ(u8.length);
303 }
304 this._rQ.set(u8, this._rQlen);
305 this._rQlen += u8.length;
306 },
fcff386b 307
6d6f0db0 308 _recv_message: function (e) {
1678bf86
PO
309 this._decode_message(e.data);
310 if (this.rQlen() > 0) {
311 this._eventHandlers.message();
312 // Compact the receive queue
313 if (this._rQlen == this._rQi) {
314 this._rQlen = 0;
315 this._rQi = 0;
316 } else if (this._rQlen > this._rQmax) {
317 this._expand_compact_rQ();
2cccf753 318 }
1678bf86
PO
319 } else {
320 Log.Debug("Ignoring empty message");
72f1348b 321 }
6d6f0db0
SR
322 }
323};