web_socket.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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.OPEN) return;
  109. this.__flash.close();
  110. // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
  111. // which causes weird error:
  112. // > You are trying to call recursively into the Flash Player which is not allowed.
  113. this.readyState = WebSocket.CLOSED;
  114. if (this.__timer) clearInterval(this.__timer);
  115. if (this.onclose) {
  116. // Make it asynchronous so that it looks more like an actual
  117. // close event
  118. setTimeout(this.onclose, 1);
  119. }
  120. };
  121. /**
  122. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  123. *
  124. * @param {string} type
  125. * @param {function} listener
  126. * @param {boolean} useCapture !NB Not implemented yet
  127. * @return void
  128. */
  129. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  130. if (!('__events' in this)) {
  131. this.__events = {};
  132. }
  133. if (!(type in this.__events)) {
  134. this.__events[type] = [];
  135. if ('function' == typeof this['on' + type]) {
  136. this.__events[type].defaultHandler = this['on' + type];
  137. this['on' + type] = this.__createEventHandler(this, type);
  138. }
  139. }
  140. this.__events[type].push(listener);
  141. };
  142. /**
  143. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  144. *
  145. * @param {string} type
  146. * @param {function} listener
  147. * @param {boolean} useCapture NB! Not implemented yet
  148. * @return void
  149. */
  150. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  151. if (!('__events' in this)) {
  152. this.__events = {};
  153. }
  154. if (!(type in this.__events)) return;
  155. for (var i = this.__events.length; i > -1; --i) {
  156. if (listener === this.__events[type][i]) {
  157. this.__events[type].splice(i, 1);
  158. break;
  159. }
  160. }
  161. };
  162. /**
  163. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  164. *
  165. * @param {WebSocketEvent} event
  166. * @return void
  167. */
  168. WebSocket.prototype.dispatchEvent = function(event) {
  169. if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  170. if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  171. for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
  172. this.__events[event.type][i](event);
  173. if (event.cancelBubble) break;
  174. }
  175. if (false !== event.returnValue &&
  176. 'function' == typeof this.__events[event.type].defaultHandler)
  177. {
  178. this.__events[event.type].defaultHandler(event);
  179. }
  180. };
  181. WebSocket.prototype.__handleMessages = function() {
  182. // Gets data using readSocketData() instead of getting it from event object
  183. // of Flash event. This is to make sure to keep message order.
  184. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  185. var arr = this.__flash.readSocketData();
  186. for (var i = 0; i < arr.length; i++) {
  187. var data = decodeURIComponent(arr[i]);
  188. try {
  189. if (this.onmessage) {
  190. var e;
  191. if (window.MessageEvent) {
  192. e = document.createEvent("MessageEvent");
  193. e.initMessageEvent("message", false, false, data, null, null, window, null);
  194. } else { // IE
  195. e = {data: data};
  196. }
  197. this.onmessage(e);
  198. }
  199. } catch (e) {
  200. console.error(e.toString());
  201. }
  202. }
  203. };
  204. /**
  205. * @param {object} object
  206. * @param {string} type
  207. */
  208. WebSocket.prototype.__createEventHandler = function(object, type) {
  209. return function(data) {
  210. var event = new WebSocketEvent();
  211. event.initEvent(type, true, true);
  212. event.target = event.currentTarget = object;
  213. for (var key in data) {
  214. event[key] = data[key];
  215. }
  216. object.dispatchEvent(event, arguments);
  217. };
  218. }
  219. /**
  220. * Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
  221. *
  222. * @class
  223. * @constructor
  224. */
  225. function WebSocketEvent(){}
  226. /**
  227. *
  228. * @type boolean
  229. */
  230. WebSocketEvent.prototype.cancelable = true;
  231. /**
  232. *
  233. * @type boolean
  234. */
  235. WebSocketEvent.prototype.cancelBubble = false;
  236. /**
  237. *
  238. * @return void
  239. */
  240. WebSocketEvent.prototype.preventDefault = function() {
  241. if (this.cancelable) {
  242. this.returnValue = false;
  243. }
  244. };
  245. /**
  246. *
  247. * @return void
  248. */
  249. WebSocketEvent.prototype.stopPropagation = function() {
  250. this.cancelBubble = true;
  251. };
  252. /**
  253. *
  254. * @param {string} eventTypeArg
  255. * @param {boolean} canBubbleArg
  256. * @param {boolean} cancelableArg
  257. * @return void
  258. */
  259. WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
  260. this.type = eventTypeArg;
  261. this.cancelable = cancelableArg;
  262. this.timeStamp = new Date();
  263. };
  264. WebSocket.CONNECTING = 0;
  265. WebSocket.OPEN = 1;
  266. WebSocket.CLOSING = 2;
  267. WebSocket.CLOSED = 3;
  268. WebSocket.__tasks = [];
  269. WebSocket.__initialize = function() {
  270. if (WebSocket.__swfLocation) {
  271. // For backword compatibility.
  272. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  273. }
  274. if (!window.WEB_SOCKET_SWF_LOCATION) {
  275. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  276. return;
  277. }
  278. var container = document.createElement("div");
  279. container.id = "webSocketContainer";
  280. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  281. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  282. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  283. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  284. // the best we can do as far as we know now.
  285. container.style.position = "absolute";
  286. if (WebSocket.__isFlashLite()) {
  287. container.style.left = "0px";
  288. container.style.top = "0px";
  289. } else {
  290. container.style.left = "-100px";
  291. container.style.top = "-100px";
  292. }
  293. var holder = document.createElement("div");
  294. holder.id = "webSocketFlash";
  295. container.appendChild(holder);
  296. document.body.appendChild(container);
  297. // See this article for hasPriority:
  298. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  299. swfobject.embedSWF(
  300. WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
  301. "1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
  302. null, {bridgeName: "webSocket"}, {hasPriority: true, allowScriptAccess: "always"}, null,
  303. function(e) {
  304. if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
  305. }
  306. );
  307. FABridge.addInitializationCallback("webSocket", function() {
  308. try {
  309. //console.log("[WebSocket] FABridge initializad");
  310. WebSocket.__flash = FABridge.webSocket.root();
  311. WebSocket.__flash.setCallerUrl(location.href);
  312. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  313. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  314. WebSocket.__tasks[i]();
  315. }
  316. WebSocket.__tasks = [];
  317. } catch (e) {
  318. console.error("[WebSocket] " + e.toString());
  319. }
  320. });
  321. };
  322. WebSocket.__addTask = function(task) {
  323. if (WebSocket.__flash) {
  324. task();
  325. } else {
  326. WebSocket.__tasks.push(task);
  327. }
  328. };
  329. WebSocket.__isFlashLite = function() {
  330. if (!window.navigator || !window.navigator.mimeTypes) return false;
  331. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  332. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
  333. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  334. };
  335. // called from Flash
  336. window.webSocketLog = function(message) {
  337. console.log(decodeURIComponent(message));
  338. };
  339. // called from Flash
  340. window.webSocketError = function(message) {
  341. console.error(decodeURIComponent(message));
  342. };
  343. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  344. if (window.addEventListener) {
  345. window.addEventListener("load", WebSocket.__initialize, false);
  346. } else {
  347. window.attachEvent("onload", WebSocket.__initialize);
  348. }
  349. }
  350. })();