Debian Codegraph @

closure-library/closure/goog/net/websocket.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Definition of the WebSocket class. A WebSocket provides a
17 * bi-directional, full-duplex communications channel, over a single TCP socket.
18 *
19 * See http://dev.w3.org/html5/websockets/
20 * for the full HTML5 WebSocket API.
21 *
22 * Typical usage will look like this:
23 *
24 * var ws = new goog.net.WebSocket();
25 *
26 * var handler = new goog.events.EventHandler();
27 * handler.listen(ws, goog.net.WebSocket.EventType.OPENED, onOpen);
28 * handler.listen(ws, goog.net.WebSocket.EventType.MESSAGE, onMessage);
29 *
30 * try {
31 * ws.open('ws://127.0.0.1:4200');
32 * } catch (e) {
33 * ...
34 * }
35 *
36 */
37
38 goog.provide('goog.net.WebSocket');
39 goog.provide('goog.net.WebSocket.ErrorEvent');
40 goog.provide('goog.net.WebSocket.EventType');
41 goog.provide('goog.net.WebSocket.MessageEvent');
42
43 goog.require('goog.Timer');
44 goog.require('goog.asserts');
45 goog.require('goog.debug.entryPointRegistry');
46 goog.require('goog.events');
47 goog.require('goog.events.Event');
48 goog.require('goog.events.EventTarget');
49 goog.require('goog.log');
50
51
52 /**
53 * Class encapsulating the logic for using a WebSocket.
54 *
55 * @param {boolean|!goog.net.WebSocket.Options=} opt_params
56 * Parameters describing behavior of the WebSocket. The boolean 'true' is
57 * equivalent to setting Options.autoReconnect to be true.
58 * @param {function(number): number=} opt_getNextReconnect
59 * @see goog.net.WebSocket.Options.getNextReconnect. This parameter is
60 * ignored if Options is passed for the first argument.
61 * @constructor
62 * @extends {goog.events.EventTarget}
63 */
64 goog.net.WebSocket = function(opt_params, opt_getNextReconnect) {
65 goog.net.WebSocket.base(this, 'constructor');
66 if (typeof opt_params != 'object') {
67 opt_params = /**@type {!goog.net.WebSocket.Options} */ ({
68 autoReconnect: opt_params,
69 getNextReconnect: opt_getNextReconnect,
70 });
71 }
72 /** @private {boolean} @see goog.net.WebSocket.Options.autoReconnect */
73 this.autoReconnect_ = opt_params.autoReconnect != false;
74 /**
75 * @private {function(number): number}
76 * @see goog.net.WebSocket.Options.getNextReconnect
77 */
78 this.getNextReconnect_ =
79 opt_params.getNextReconnect || goog.net.WebSocket.EXPONENTIAL_BACKOFF_;
80 /**
81 * @private {goog.net.WebSocket.BinaryType}
82 * @see goog.net.WebSocket.Options.binaryType
83 */
84 this.binaryType_ =
85 opt_params.binaryType || goog.net.WebSocket.BinaryType.BLOB;
86
87 /**
88 * The time, in milliseconds, that must elapse before the next attempt to
89 * reconnect.
90 * @type {number}
91 * @private
92 */
93 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);
94 };
95 goog.inherits(goog.net.WebSocket, goog.events.EventTarget);
96
97
98 /** @enum {string} */
99 goog.net.WebSocket.BinaryType = {
100 ARRAY_BUFFER: 'arraybuffer',
101 BLOB: 'blob',
102 };
103
104
105 /** @record */
106 goog.net.WebSocket.Options = function() {
107
108 /**
109 * True if the web socket should automatically reconnect or not. This is
110 * true by default.
111 * @type {boolean|undefined}
112 */
113 this.autoReconnect;
114
115 /**
116 * A function for obtaining the time until the next reconnect attempt. Given
117 * the reconnect attempt count (which is a positive integer), the function
118 * should return a positive integer representing the milliseconds to the
119 * next reconnect attempt. The default function used is an exponential
120 * back-off. Note that this function is never called if auto reconnect is
121 * disabled.
122 * @type {(function(number): number)|undefined}
123 */
124 this.getNextReconnect;
125
126 /**
127 * Specifies the type of incoming binary messages, either Blob or
128 * ArrayBuffer.
129 * @type {!goog.net.WebSocket.BinaryType|undefined}
130 */
131 this.binaryType;
132 };
133
134 /**
135 * The actual web socket that will be used to send/receive messages.
136 * @type {?WebSocket}
137 * @private
138 */
139 goog.net.WebSocket.prototype.webSocket_ = null;
140
141
142 /**
143 * The URL to which the web socket will connect.
144 * @type {?string}
145 * @private
146 */
147 goog.net.WebSocket.prototype.url_ = null;
148
149
150 /**
151 * The subprotocol name used when establishing the web socket connection.
152 * @type {string|undefined}
153 * @private
154 */
155 goog.net.WebSocket.prototype.protocol_ = undefined;
156
157
158 /**
159 * True if a call to the close callback is expected or not.
160 * @type {boolean}
161 * @private
162 */
163 goog.net.WebSocket.prototype.closeExpected_ = false;
164
165
166 /**
167 * Keeps track of the number of reconnect attempts made since the last
168 * successful connection.
169 * @type {number}
170 * @private
171 */
172 goog.net.WebSocket.prototype.reconnectAttempt_ = 0;
173
174
175 /** @private {?number} */
176 goog.net.WebSocket.prototype.reconnectTimer_ = null;
177
178
179 /**
180 * The logger for this class.
181 * @type {?goog.log.Logger}
182 * @private
183 */
184 goog.net.WebSocket.prototype.logger_ = goog.log.getLogger('goog.net.WebSocket');
185
186
187 /**
188 * The events fired by the web socket.
189 * @enum {string} The event types for the web socket.
190 */
191 goog.net.WebSocket.EventType = {
192
193 /**
194 * Fired when an attempt to open the WebSocket fails or there is a connection
195 * failure after a successful connection has been established.
196 */
197 CLOSED: goog.events.getUniqueId('closed'),
198
199 /**
200 * Fired when the WebSocket encounters an error.
201 */
202 ERROR: goog.events.getUniqueId('error'),
203
204 /**
205 * Fired when a new message arrives from the WebSocket.
206 */
207 MESSAGE: goog.events.getUniqueId('message'),
208
209 /**
210 * Fired when the WebSocket connection has been established.
211 */
212 OPENED: goog.events.getUniqueId('opened')
213 };
214
215
216 /**
217 * The various states of the web socket.
218 * @enum {number} The states of the web socket.
219 * @private
220 */
221 goog.net.WebSocket.ReadyState_ = {
222 // This is the initial state during construction.
223 CONNECTING: 0,
224 // This is when the socket is actually open and ready for data.
225 OPEN: 1,
226 // This is when the socket is in the middle of a close handshake.
227 // Note that this is a valid state even if the OPEN state was never achieved.
228 CLOSING: 2,
229 // This is when the socket is actually closed.
230 CLOSED: 3
231 };
232
233 /**
234 * The maximum amount of time between reconnect attempts for the exponential
235 * back-off in milliseconds.
236 * @type {number}
237 * @private
238 */
239 goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_ = 60 * 1000;
240
241
242 /**
243 * Computes the next reconnect time given the number of reconnect attempts since
244 * the last successful connection.
245 *
246 * @param {number} attempt The number of reconnect attempts since the last
247 * connection.
248 * @return {number} The time, in milliseconds, until the next reconnect attempt.
249 * @const
250 * @private
251 */
252 goog.net.WebSocket.EXPONENTIAL_BACKOFF_ = function(attempt) {
253 var time = Math.pow(2, attempt) * 1000;
254 return Math.min(time, goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_);
255 };
256
257
258 /**
259 * Installs exception protection for all entry points introduced by
260 * goog.net.WebSocket instances which are not protected by
261 * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
262 * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
263 * {@link goog.events.protectBrowserEventEntryPoint}.
264 *
265 * @param {!goog.debug.ErrorHandler} errorHandler Error handler with which to
266 * protect the entry points.
267 */
268 goog.net.WebSocket.protectEntryPoints = function(errorHandler) {
269 goog.net.WebSocket.prototype.onOpen_ =
270 errorHandler.protectEntryPoint(goog.net.WebSocket.prototype.onOpen_);
271 goog.net.WebSocket.prototype.onClose_ =
272 errorHandler.protectEntryPoint(goog.net.WebSocket.prototype.onClose_);
273 goog.net.WebSocket.prototype.onMessage_ =
274 errorHandler.protectEntryPoint(goog.net.WebSocket.prototype.onMessage_);
275 goog.net.WebSocket.prototype.onError_ =
276 errorHandler.protectEntryPoint(goog.net.WebSocket.prototype.onError_);
277 };
278
279
280 /**
281 * Creates and opens the actual WebSocket. Only call this after attaching the
282 * appropriate listeners to this object. If listeners aren't registered, then
283 * the {@code goog.net.WebSocket.EventType.OPENED} event might be missed.
284 *
285 * @param {string} url The URL to which to connect.
286 * @param {string=} opt_protocol The subprotocol to use. The connection will
287 * only be established if the server reports that it has selected this
288 * subprotocol. The subprotocol name must all be a non-empty ASCII string
289 * with no control characters and no spaces in them (i.e. only characters
290 * in the range U+0021 to U+007E).
291 */
292 goog.net.WebSocket.prototype.open = function(url, opt_protocol) {
293 // Sanity check. This works only in modern browsers.
294 goog.asserts.assert(
295 goog.global['WebSocket'], 'This browser does not support WebSocket');
296
297 // Don't do anything if the web socket is already open.
298 goog.asserts.assert(!this.isOpen(), 'The WebSocket is already open');
299
300 // Clear any pending attempts to reconnect.
301 this.clearReconnectTimer_();
302
303 // Construct the web socket.
304 this.url_ = url;
305 this.protocol_ = opt_protocol;
306
307 // This check has to be made otherwise you get protocol mismatch exceptions
308 // for passing undefined, null, '', or [].
309 if (this.protocol_) {
310 goog.log.info(
311 this.logger_, 'Opening the WebSocket on ' + this.url_ +
312 ' with protocol ' + this.protocol_);
313 this.webSocket_ = new WebSocket(this.url_, this.protocol_);
314 } else {
315 goog.log.info(this.logger_, 'Opening the WebSocket on ' + this.url_);
316 this.webSocket_ = new WebSocket(this.url_);
317 }
318 this.webSocket_.binaryType = this.binaryType_;
319 // Register the event handlers. Note that it is not possible for these
320 // callbacks to be missed because it is registered after the web socket is
321 // instantiated. Because of the synchronous nature of JavaScript, this code
322 // will execute before the browser creates the resource and makes any calls
323 // to these callbacks.
324 this.webSocket_.onopen = goog.bind(this.onOpen_, this);
325 this.webSocket_.onclose = goog.bind(this.onClose_, this);
326 this.webSocket_.onmessage = goog.bind(this.onMessage_, this);
327 this.webSocket_.onerror = goog.bind(this.onError_, this);
328 };
329
330
331 /**
332 * Closes the web socket connection.
333 */
334 goog.net.WebSocket.prototype.close = function() {
335
336 // Clear any pending attempts to reconnect.
337 this.clearReconnectTimer_();
338
339 // Attempt to close only if the web socket was created.
340 if (this.webSocket_) {
341 goog.log.info(this.logger_, 'Closing the WebSocket.');
342
343 // Close is expected here since it was a direct call. Close is considered
344 // unexpected when opening the connection fails or there is some other form
345 // of connection loss after being connected.
346 this.closeExpected_ = true;
347 this.webSocket_.close();
348 this.webSocket_ = null;
349 }
350 };
351
352
353 /**
354 * Sends the message over the web socket.
355 *
356 * @param {string|!ArrayBuffer|!ArrayBufferView} message The message to send.
357 */
358 goog.net.WebSocket.prototype.send = function(message) {
359 // Make sure the socket is ready to go before sending a message.
360 goog.asserts.assert(this.isOpen(), 'Cannot send without an open socket');
361
362 // Send the message and let onError_ be called if it fails thereafter.
363 this.webSocket_.send(message);
364 };
365
366
367 /**
368 * Checks to see if the web socket is open or not.
369 *
370 * @return {boolean} True if the web socket is open, false otherwise.
371 */
372 goog.net.WebSocket.prototype.isOpen = function() {
373 return !!this.webSocket_ &&
374 this.webSocket_.readyState == goog.net.WebSocket.ReadyState_.OPEN;
375 };
376
377
378 /**
379 * Gets the number of bytes of data that have been queued using calls to send()
380 * but not yet transmitted to the network.
381 *
382 * @return {number} Number of bytes of data that have been queued.
383 */
384 goog.net.WebSocket.prototype.getBufferedAmount = function() {
385 return this.webSocket_.bufferedAmount;
386 };
387
388
389 /**
390 * Called when the web socket has connected.
391 *
392 * @private
393 */
394 goog.net.WebSocket.prototype.onOpen_ = function() {
395 goog.log.info(this.logger_, 'WebSocket opened on ' + this.url_);
396 this.dispatchEvent(goog.net.WebSocket.EventType.OPENED);
397
398 // Set the next reconnect interval.
399 this.reconnectAttempt_ = 0;
400 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);
401 };
402
403
404 /**
405 * Called when the web socket has closed.
406 *
407 * @param {!Event} event The close event.
408 * @private
409 */
410 goog.net.WebSocket.prototype.onClose_ = function(event) {
411 goog.log.info(this.logger_, 'The WebSocket on ' + this.url_ + ' closed.');
412
413 // Firing this event allows handlers to query the URL.
414 this.dispatchEvent(goog.net.WebSocket.EventType.CLOSED);
415
416 // Always clear out the web socket on a close event.
417 this.webSocket_ = null;
418
419 // See if this is an expected call to onClose_.
420 if (this.closeExpected_) {
421 goog.log.info(this.logger_, 'The WebSocket closed normally.');
422 // Only clear out the URL if this is a normal close.
423 this.url_ = null;
424 this.protocol_ = undefined;
425 } else {
426 // Unexpected, so try to reconnect.
427 goog.log.error(
428 this.logger_, 'The WebSocket disconnected unexpectedly: ' + event.data);
429
430 // Only try to reconnect if it is enabled.
431 if (this.autoReconnect_) {
432 // Log the reconnect attempt.
433 var seconds = Math.floor(this.nextReconnect_ / 1000);
434 goog.log.info(
435 this.logger_, 'Seconds until next reconnect attempt: ' + seconds);
436
437 // Actually schedule the timer.
438 this.reconnectTimer_ = goog.Timer.callOnce(
439 goog.bind(this.open, this, this.url_, this.protocol_),
440 this.nextReconnect_, this);
441
442 // Set the next reconnect interval.
443 this.reconnectAttempt_++;
444 this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_);
445 }
446 }
447 this.closeExpected_ = false;
448 };
449
450
451 /**
452 * Called when a new message arrives from the server.
453 *
454 * @param {MessageEvent<string>} event The web socket message event.
455 * @private
456 */
457 goog.net.WebSocket.prototype.onMessage_ = function(event) {
458 var message = event.data;
459 this.dispatchEvent(new goog.net.WebSocket.MessageEvent(message));
460 };
461
462
463 /**
464 * Called when there is any error in communication.
465 *
466 * @param {Event} event The error event containing the error data.
467 * @private
468 */
469 goog.net.WebSocket.prototype.onError_ = function(event) {
470 var data = /** @type {string} */ (event.data);
471 goog.log.error(this.logger_, 'An error occurred: ' + data);
472 this.dispatchEvent(new goog.net.WebSocket.ErrorEvent(data));
473 };
474
475
476 /**
477 * Clears the reconnect timer.
478 *
479 * @private
480 */
481 goog.net.WebSocket.prototype.clearReconnectTimer_ = function() {
482 if (goog.isDefAndNotNull(this.reconnectTimer_)) {
483 goog.Timer.clear(this.reconnectTimer_);
484 }
485 this.reconnectTimer_ = null;
486 };
487
488
489 /** @override */
490 goog.net.WebSocket.prototype.disposeInternal = function() {
491 goog.net.WebSocket.base(this, 'disposeInternal');
492 this.close();
493 };
494
495
496 /**
497 * Object representing a new incoming message event.
498 *
499 * @param {string} message The raw message coming from the web socket.
500 * @extends {goog.events.Event}
501 * @constructor
502 * @final
503 */
504 goog.net.WebSocket.MessageEvent = function(message) {
505 goog.net.WebSocket.MessageEvent.base(
506 this, 'constructor', goog.net.WebSocket.EventType.MESSAGE);
507
508 /**
509 * The new message from the web socket.
510 * @type {string}
511 */
512 this.message = message;
513 };
514 goog.inherits(goog.net.WebSocket.MessageEvent, goog.events.Event);
515
516
517 /**
518 * Object representing an error event. This is fired whenever an error occurs
519 * on the web socket.
520 *
521 * @param {string} data The error data.
522 * @extends {goog.events.Event}
523 * @constructor
524 * @final
525 */
526 goog.net.WebSocket.ErrorEvent = function(data) {
527 goog.net.WebSocket.ErrorEvent.base(
528 this, 'constructor', goog.net.WebSocket.EventType.ERROR);
529
530 /**
531 * The error data coming from the web socket.
532 * @type {string}
533 */
534 this.data = data;
535 };
536 goog.inherits(goog.net.WebSocket.ErrorEvent, goog.events.Event);
537
538
539 // Register the WebSocket as an entry point, so that it can be monitored for
540 // exception handling, etc.
541 goog.debug.entryPointRegistry.register(
542 /**
543 * @param {function(!Function): !Function} transformer The transforming
544 * function.
545 */
546 function(transformer) {
547 goog.net.WebSocket.prototype.onOpen_ =
548 transformer(goog.net.WebSocket.prototype.onOpen_);
549 goog.net.WebSocket.prototype.onClose_ =
550 transformer(goog.net.WebSocket.prototype.onClose_);
551 goog.net.WebSocket.prototype.onMessage_ =
552 transformer(goog.net.WebSocket.prototype.onMessage_);
553 goog.net.WebSocket.prototype.onError_ =
554 transformer(goog.net.WebSocket.prototype.onError_);
555 });