web_socket.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  2. // License: New BSD License
  3. // Reference: http://dev.w3.org/html5/websockets/
  4. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  5. (function() {
  6. if (window.WebSocket) return;
  7. var console = window.console;
  8. if (!console) console = {log: function(){ }, error: function(){ }};
  9. if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
  10. console.error("Flash Player is not installed.");
  11. return;
  12. }
  13. if (location.protocol == "file:") {
  14. console.error(
  15. "WARNING: web-socket-js doesn't work in file:///... URL " +
  16. "unless you set Flash Security Settings properly. " +
  17. "Open the page via Web server i.e. http://...");
  18. }
  19. WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
  20. var self = this;
  21. self.readyState = WebSocket.CONNECTING;
  22. self.bufferedAmount = 0;
  23. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  24. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  25. setTimeout(function() {
  26. WebSocket.__addTask(function() {
  27. self.__createFlash(url, protocol, proxyHost, proxyPort, headers);
  28. });
  29. }, 1);
  30. }
  31. WebSocket.prototype.__createFlash = function(url, protocol, proxyHost, proxyPort, headers) {
  32. var self = this;
  33. self.__flash =
  34. WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
  35. self.__flash.addEventListener("open", function(fe) {
  36. try {
  37. self.readyState = self.__flash.getReadyState();
  38. if (self.__timer) clearInterval(self.__timer);
  39. if (window.opera) {
  40. // Workaround for weird behavior of Opera which sometimes drops events.
  41. self.__timer = setInterval(function () {
  42. self.__handleMessages();
  43. }, 500);
  44. }
  45. if (self.onopen) self.onopen();
  46. } catch (e) {
  47. console.error(e.toString());
  48. }
  49. });
  50. self.__flash.addEventListener("close", function(fe) {
  51. try {
  52. self.readyState = self.__flash.getReadyState();
  53. if (self.__timer) clearInterval(self.__timer);
  54. if (self.onclose) self.onclose();
  55. } catch (e) {
  56. console.error(e.toString());
  57. }
  58. });
  59. self.__flash.addEventListener("message", function() {
  60. try {
  61. self.__handleMessages();
  62. } catch (e) {
  63. console.error(e.toString());
  64. }
  65. });
  66. self.__flash.addEventListener("error", function(fe) {
  67. try {
  68. if (self.__timer) clearInterval(self.__timer);
  69. if (self.onerror) self.onerror();
  70. } catch (e) {
  71. console.error(e.toString());
  72. }
  73. });
  74. self.__flash.addEventListener("stateChange", function(fe) {
  75. try {
  76. self.readyState = self.__flash.getReadyState();
  77. self.bufferedAmount = fe.getBufferedAmount();
  78. } catch (e) {
  79. console.error(e.toString());
  80. }
  81. });
  82. //console.log("[WebSocket] Flash object is ready");
  83. };
  84. WebSocket.prototype.send = function(data) {
  85. if (this.__flash) {
  86. this.readyState = this.__flash.getReadyState();
  87. }
  88. if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
  89. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  90. }
  91. // We use encodeURIComponent() here, because FABridge doesn't work if
  92. // the argument includes some characters. We don't use escape() here
  93. // because of this:
  94. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  95. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  96. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  97. var result = this.__flash.send(encodeURIComponent(data));
  98. if (result < 0) { // success
  99. return true;
  100. } else {
  101. this.bufferedAmount = result;
  102. return false;
  103. }
  104. };
  105. WebSocket.prototype.close = function() {
  106. if (!this.__flash) return;
  107. this.readyState = this.__flash.getReadyState();
  108. if ((this.readyState === WebSocket.CLOSED) ||
  109. (this.readState === WebSocket.CLOSING)) {
  110. return;
  111. }
  112. this.__flash.close();
  113. // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
  114. // which causes weird error:
  115. // > You are trying to call recursively into the Flash Player which is not allowed.
  116. this.readyState = WebSocket.CLOSED;
  117. if (this.__timer) clearInterval(this.__timer);
  118. if (this.onclose) {
  119. // Make it asynchronous so that it looks more like an actual
  120. // close event
  121. setTimeout(this.onclose, 1);
  122. }
  123. };
  124. /**
  125. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  126. *
  127. * @param {string} type
  128. * @param {function} listener
  129. * @param {boolean} useCapture !NB Not implemented yet
  130. * @return void
  131. */
  132. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  133. if (!('__events' in this)) {
  134. this.__events = {};
  135. }
  136. if (!(type in this.__events)) {
  137. this.__events[type] = [];
  138. if ('function' == typeof this['on' + type]) {
  139. this.__events[type].defaultHandler = this['on' + type];
  140. this['on' + type] = this.__createEventHandler(this, type);
  141. }
  142. }
  143. this.__events[type].push(listener);
  144. };
  145. /**
  146. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  147. *
  148. * @param {string} type
  149. * @param {function} listener
  150. * @param {boolean} useCapture NB! Not implemented yet
  151. * @return void
  152. */
  153. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  154. if (!('__events' in this)) {
  155. this.__events = {};
  156. }
  157. if (!(type in this.__events)) return;
  158. for (var i = this.__events.length; i > -1; --i) {
  159. if (listener === this.__events[type][i]) {
  160. this.__events[type].splice(i, 1);
  161. break;
  162. }
  163. }
  164. };
  165. /**
  166. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  167. *
  168. * @param {WebSocketEvent} event
  169. * @return void
  170. */
  171. WebSocket.prototype.dispatchEvent = function(event) {
  172. if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  173. if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  174. for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
  175. this.__events[event.type][i](event);
  176. if (event.cancelBubble) break;
  177. }
  178. if (false !== event.returnValue &&
  179. 'function' == typeof this.__events[event.type].defaultHandler)
  180. {
  181. this.__events[event.type].defaultHandler(event);
  182. }
  183. };
  184. WebSocket.prototype.__handleMessages = function() {
  185. // Gets data using readSocketData() instead of getting it from event object
  186. // of Flash event. This is to make sure to keep message order.
  187. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  188. var arr = this.__flash.readSocketData();
  189. for (var i = 0; i < arr.length; i++) {
  190. var data = decodeURIComponent(arr[i]);
  191. try {
  192. if (this.onmessage) {
  193. var e;
  194. if (window.MessageEvent) {
  195. e = document.createEvent("MessageEvent");
  196. e.initMessageEvent("message", false, false, data, null, null, window, null);
  197. } else { // IE
  198. e = {data: data};
  199. }
  200. this.onmessage(e);
  201. }
  202. } catch (e) {
  203. console.error(e.toString());
  204. }
  205. }
  206. };
  207. /**
  208. * @param {object} object
  209. * @param {string} type
  210. */
  211. WebSocket.prototype.__createEventHandler = function(object, type) {
  212. return function(data) {
  213. var event = new WebSocketEvent();
  214. event.initEvent(type, true, true);
  215. event.target = event.currentTarget = object;
  216. for (var key in data) {
  217. event[key] = data[key];
  218. }
  219. object.dispatchEvent(event, arguments);
  220. };
  221. }
  222. /**
  223. * Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
  224. *
  225. * @class
  226. * @constructor
  227. */
  228. function WebSocketEvent(){}
  229. /**
  230. *
  231. * @type boolean
  232. */
  233. WebSocketEvent.prototype.cancelable = true;
  234. /**
  235. *
  236. * @type boolean
  237. */
  238. WebSocketEvent.prototype.cancelBubble = false;
  239. /**
  240. *
  241. * @return void
  242. */
  243. WebSocketEvent.prototype.preventDefault = function() {
  244. if (this.cancelable) {
  245. this.returnValue = false;
  246. }
  247. };
  248. /**
  249. *
  250. * @return void
  251. */
  252. WebSocketEvent.prototype.stopPropagation = function() {
  253. this.cancelBubble = true;
  254. };
  255. /**
  256. *
  257. * @param {string} eventTypeArg
  258. * @param {boolean} canBubbleArg
  259. * @param {boolean} cancelableArg
  260. * @return void
  261. */
  262. WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
  263. this.type = eventTypeArg;
  264. this.cancelable = cancelableArg;
  265. this.timeStamp = new Date();
  266. };
  267. WebSocket.CONNECTING = 0;
  268. WebSocket.OPEN = 1;
  269. WebSocket.CLOSING = 2;
  270. WebSocket.CLOSED = 3;
  271. WebSocket.__tasks = [];
  272. WebSocket.__initialize = function() {
  273. if (WebSocket.__swfLocation) {
  274. // For backword compatibility.
  275. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  276. }
  277. if (!window.WEB_SOCKET_SWF_LOCATION) {
  278. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  279. return;
  280. }
  281. var container = document.createElement("div");
  282. container.id = "webSocketContainer";
  283. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  284. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  285. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  286. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  287. // the best we can do as far as we know now.
  288. container.style.position = "absolute";
  289. if (WebSocket.__isFlashLite()) {
  290. container.style.left = "0px";
  291. container.style.top = "0px";
  292. } else {
  293. container.style.left = "-100px";
  294. container.style.top = "-100px";
  295. }
  296. var holder = document.createElement("div");
  297. holder.id = "webSocketFlash";
  298. container.appendChild(holder);
  299. document.body.appendChild(container);
  300. // See this article for hasPriority:
  301. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  302. swfobject.embedSWF(
  303. WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
  304. "1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
  305. null, {bridgeName: "webSocket"}, {hasPriority: true, allowScriptAccess: "always"}, null,
  306. function(e) {
  307. if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
  308. }
  309. );
  310. FABridge.addInitializationCallback("webSocket", function() {
  311. try {
  312. //console.log("[WebSocket] FABridge initializad");
  313. WebSocket.__flash = FABridge.webSocket.root();
  314. WebSocket.__flash.setCallerUrl(location.href);
  315. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  316. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  317. WebSocket.__tasks[i]();
  318. }
  319. WebSocket.__tasks = [];
  320. } catch (e) {
  321. console.error("[WebSocket] " + e.toString());
  322. }
  323. });
  324. };
  325. WebSocket.__addTask = function(task) {
  326. if (WebSocket.__flash) {
  327. task();
  328. } else {
  329. WebSocket.__tasks.push(task);
  330. }
  331. };
  332. WebSocket.__isFlashLite = function() {
  333. if (!window.navigator || !window.navigator.mimeTypes) return false;
  334. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  335. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
  336. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  337. };
  338. // called from Flash
  339. window.webSocketLog = function(message) {
  340. console.log(decodeURIComponent(message));
  341. };
  342. // called from Flash
  343. window.webSocketError = function(message) {
  344. console.error(decodeURIComponent(message));
  345. };
  346. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  347. if (window.addEventListener) {
  348. window.addEventListener("load", WebSocket.__initialize, false);
  349. } else {
  350. window.attachEvent("onload", WebSocket.__initialize);
  351. }
  352. }
  353. })();