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