]>
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 | ||
6d6f0db0 | 15 | import * as Log from './util/logging.js'; |
ae510306 | 16 | |
2cccf753 | 17 | /*jslint browser: true, bitwise: true */ |
38781d93 | 18 | /*global Util*/ |
ff4bfcb7 | 19 | |
3ae0bb09 | 20 | export 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. | |
48 | var ENABLE_COPYWITHIN = false; | |
49 | ||
50 | var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB | |
51 | ||
52 | var 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 |
67 | Websock.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 | 170 | flush: function () { |
6d6f0db0 SR |
171 | if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { |
172 | this._websocket.send(this._encode_message()); | |
173 | this._sQlen = 0; | |
174 | } | |
175 | }, | |
176 | ||
177 | send: function (arr) { | |
178 | this._sQ.set(arr, this._sQlen); | |
179 | this._sQlen += arr.length; | |
180 | this.flush(); | |
181 | }, | |
182 | ||
183 | send_string: function (str) { | |
184 | this.send(str.split('').map(function (chr) { | |
185 | return chr.charCodeAt(0); | |
186 | })); | |
187 | }, | |
188 | ||
189 | // Event Handlers | |
190 | off: function (evt) { | |
191 | this._eventHandlers[evt] = function () {}; | |
192 | }, | |
193 | ||
194 | on: function (evt, handler) { | |
195 | this._eventHandlers[evt] = handler; | |
196 | }, | |
197 | ||
198 | _allocate_buffers: function () { | |
199 | this._rQ = new Uint8Array(this._rQbufferSize); | |
200 | this._sQ = new Uint8Array(this._sQbufferSize); | |
201 | }, | |
202 | ||
203 | init: function () { | |
204 | this._allocate_buffers(); | |
205 | this._rQi = 0; | |
206 | this._websocket = null; | |
207 | }, | |
208 | ||
209 | open: function (uri, protocols) { | |
210 | var ws_schema = uri.match(/^([a-z]+):\/\//)[1]; | |
211 | this.init(); | |
212 | ||
213 | this._websocket = new WebSocket(uri, protocols); | |
214 | this._websocket.binaryType = 'arraybuffer'; | |
215 | ||
216 | this._websocket.onmessage = this._recv_message.bind(this); | |
217 | this._websocket.onopen = (function () { | |
218 | Log.Debug('>> WebSock.onopen'); | |
219 | if (this._websocket.protocol) { | |
220 | Log.Info("Server choose sub-protocol: " + this._websocket.protocol); | |
2cccf753 | 221 | } |
2cccf753 | 222 | |
6d6f0db0 SR |
223 | this._eventHandlers.open(); |
224 | Log.Debug("<< WebSock.onopen"); | |
225 | }).bind(this); | |
226 | this._websocket.onclose = (function (e) { | |
227 | Log.Debug(">> WebSock.onclose"); | |
228 | this._eventHandlers.close(e); | |
229 | Log.Debug("<< WebSock.onclose"); | |
230 | }).bind(this); | |
231 | this._websocket.onerror = (function (e) { | |
232 | Log.Debug(">> WebSock.onerror: " + e); | |
233 | this._eventHandlers.error(e); | |
234 | Log.Debug("<< WebSock.onerror: " + e); | |
235 | }).bind(this); | |
236 | }, | |
237 | ||
238 | close: function () { | |
239 | if (this._websocket) { | |
240 | if ((this._websocket.readyState === WebSocket.OPEN) || | |
241 | (this._websocket.readyState === WebSocket.CONNECTING)) { | |
242 | Log.Info("Closing WebSocket connection"); | |
243 | this._websocket.close(); | |
fcff386b | 244 | } |
6d6f0db0 SR |
245 | |
246 | this._websocket.onmessage = function (e) { return; }; | |
247 | } | |
248 | }, | |
249 | ||
250 | // private methods | |
251 | _encode_message: function () { | |
252 | // Put in a binary arraybuffer | |
253 | // according to the spec, you can send ArrayBufferViews with the send method | |
254 | return new Uint8Array(this._sQ.buffer, 0, this._sQlen); | |
255 | }, | |
256 | ||
257 | _expand_compact_rQ: function (min_fit) { | |
258 | var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; | |
259 | if (resizeNeeded) { | |
260 | if (!min_fit) { | |
261 | // just double the size if we need to do compaction | |
262 | this._rQbufferSize *= 2; | |
263 | } else { | |
264 | // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 | |
265 | this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8; | |
40037b6a | 266 | } |
6d6f0db0 | 267 | } |
40037b6a | 268 | |
6d6f0db0 SR |
269 | // we don't want to grow unboundedly |
270 | if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { | |
271 | this._rQbufferSize = MAX_RQ_GROW_SIZE; | |
272 | if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) { | |
273 | throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); | |
40037b6a | 274 | } |
6d6f0db0 | 275 | } |
40037b6a | 276 | |
6d6f0db0 SR |
277 | if (resizeNeeded) { |
278 | var old_rQbuffer = this._rQ.buffer; | |
279 | this._rQmax = this._rQbufferSize / 8; | |
280 | this._rQ = new Uint8Array(this._rQbufferSize); | |
281 | this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); | |
282 | } else { | |
283 | if (ENABLE_COPYWITHIN) { | |
284 | this._rQ.copyWithin(0, this._rQi); | |
40037b6a | 285 | } else { |
6d6f0db0 | 286 | this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); |
40037b6a | 287 | } |
6d6f0db0 | 288 | } |
40037b6a | 289 | |
6d6f0db0 SR |
290 | this._rQlen = this._rQlen - this._rQi; |
291 | this._rQi = 0; | |
292 | }, | |
40037b6a | 293 | |
6d6f0db0 SR |
294 | _decode_message: function (data) { |
295 | // push arraybuffer values onto the end | |
296 | var u8 = new Uint8Array(data); | |
297 | if (u8.length > this._rQbufferSize - this._rQlen) { | |
298 | this._expand_compact_rQ(u8.length); | |
299 | } | |
300 | this._rQ.set(u8, this._rQlen); | |
301 | this._rQlen += u8.length; | |
302 | }, | |
fcff386b | 303 | |
6d6f0db0 | 304 | _recv_message: function (e) { |
1678bf86 PO |
305 | this._decode_message(e.data); |
306 | if (this.rQlen() > 0) { | |
307 | this._eventHandlers.message(); | |
308 | // Compact the receive queue | |
309 | if (this._rQlen == this._rQi) { | |
310 | this._rQlen = 0; | |
311 | this._rQi = 0; | |
312 | } else if (this._rQlen > this._rQmax) { | |
313 | this._expand_compact_rQ(); | |
2cccf753 | 314 | } |
1678bf86 PO |
315 | } else { |
316 | Log.Debug("Ignoring empty message"); | |
72f1348b | 317 | } |
6d6f0db0 SR |
318 | } |
319 | }; |