web_socket.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 || !console.error) {
  9. console = {log: function(){ }, error: function(){ }};
  10. }
  11. if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
  12. console.error("Flash Player >= 10.0.0 is required.");
  13. return;
  14. }
  15. if (location.protocol == "file:") {
  16. console.error(
  17. "WARNING: web-socket-js doesn't work in file:///... URL " +
  18. "unless you set Flash Security Settings properly. " +
  19. "Open the page via Web server i.e. http://...");
  20. }
  21. /**
  22. * This class represents a faux web socket.
  23. * @param {string} url
  24. * @param {string} protocol
  25. * @param {string} proxyHost
  26. * @param {int} proxyPort
  27. * @param {string} headers
  28. */
  29. WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
  30. var self = this;
  31. self.__id = WebSocket.__nextId++;
  32. WebSocket.__instances[self.__id] = self;
  33. self.readyState = WebSocket.CONNECTING;
  34. self.bufferedAmount = 0;
  35. self.__events = {};
  36. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  37. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  38. setTimeout(function() {
  39. WebSocket.__addTask(function() {
  40. WebSocket.__flash.create(
  41. self.__id, url, protocol, proxyHost || null, proxyPort || 0, headers || null);
  42. });
  43. }, 0);
  44. };
  45. /**
  46. * Send data to the web socket.
  47. * @param {string} data The data to send to the socket.
  48. * @return {boolean} True for success, false for failure.
  49. */
  50. WebSocket.prototype.send = function(data) {
  51. if (this.readyState == WebSocket.CONNECTING) {
  52. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  53. }
  54. // We use encodeURIComponent() here, because FABridge doesn't work if
  55. // the argument includes some characters. We don't use escape() here
  56. // because of this:
  57. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  58. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  59. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  60. // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
  61. // additional testing.
  62. var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
  63. if (result < 0) { // success
  64. return true;
  65. } else {
  66. this.bufferedAmount += result;
  67. return false;
  68. }
  69. };
  70. /**
  71. * Close this web socket gracefully.
  72. */
  73. WebSocket.prototype.close = function() {
  74. if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
  75. return;
  76. }
  77. this.readyState = WebSocket.CLOSING;
  78. WebSocket.__flash.close(this.__id);
  79. };
  80. /**
  81. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  82. *
  83. * @param {string} type
  84. * @param {function} listener
  85. * @param {boolean} useCapture
  86. * @return void
  87. */
  88. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  89. if (!(type in this.__events)) {
  90. this.__events[type] = [];
  91. }
  92. this.__events[type].push(listener);
  93. };
  94. /**
  95. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  96. *
  97. * @param {string} type
  98. * @param {function} listener
  99. * @param {boolean} useCapture
  100. * @return void
  101. */
  102. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  103. if (!(type in this.__events)) return;
  104. var events = this.__events[type];
  105. for (var i = events.length - 1; i >= 0; --i) {
  106. if (events[i] === listener) {
  107. events.splice(i, 1);
  108. break;
  109. }
  110. }
  111. };
  112. /**
  113. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  114. *
  115. * @param {Event} event
  116. * @return void
  117. */
  118. WebSocket.prototype.dispatchEvent = function(event) {
  119. var events = this.__events[event.type] || [];
  120. for (var i = 0; i < events.length; ++i) {
  121. events[i](event);
  122. }
  123. var handler = this["on" + event.type];
  124. if (handler) handler(event);
  125. };
  126. /**
  127. * Handles an event from Flash.
  128. * @param {Object} flashEvent
  129. */
  130. WebSocket.prototype.__handleEvent = function(flashEvent) {
  131. if ("readyState" in flashEvent) {
  132. this.readyState = flashEvent.readyState;
  133. }
  134. var jsEvent;
  135. if (flashEvent.type == "open" || flashEvent.type == "error") {
  136. jsEvent = this.__createSimpleEvent(flashEvent.type);
  137. } else if (flashEvent.type == "close") {
  138. // TODO implement jsEvent.wasClean
  139. jsEvent = this.__createSimpleEvent("close");
  140. } else if (flashEvent.type == "message") {
  141. var data = decodeURIComponent(flashEvent.message);
  142. jsEvent = this.__createMessageEvent("message", data);
  143. } else {
  144. throw "unknown event type: " + flashEvent.type;
  145. }
  146. this.dispatchEvent(jsEvent);
  147. };
  148. WebSocket.prototype.__createSimpleEvent = function(type) {
  149. if (document.createEvent && window.Event) {
  150. var event = document.createEvent("Event");
  151. event.initEvent(type, false, false);
  152. return event;
  153. } else {
  154. return {type: type, bubbles: false, cancelable: false};
  155. }
  156. };
  157. WebSocket.prototype.__createMessageEvent = function(type, data) {
  158. if (document.createEvent && window.MessageEvent && !window.opera) {
  159. var event = document.createEvent("MessageEvent");
  160. event.initMessageEvent("message", false, false, data, null, null, window, null);
  161. return event;
  162. } else {
  163. // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
  164. return {type: type, data: data, bubbles: false, cancelable: false};
  165. }
  166. };
  167. /**
  168. * Define the WebSocket readyState enumeration.
  169. */
  170. WebSocket.CONNECTING = 0;
  171. WebSocket.OPEN = 1;
  172. WebSocket.CLOSING = 2;
  173. WebSocket.CLOSED = 3;
  174. WebSocket.__flash = null;
  175. WebSocket.__instances = {};
  176. WebSocket.__tasks = [];
  177. WebSocket.__nextId = 0;
  178. /**
  179. * Load a new flash security policy file.
  180. * @param {string} url
  181. */
  182. WebSocket.loadFlashPolicyFile = function(url){
  183. WebSocket.__addTask(function() {
  184. WebSocket.__flash.loadManualPolicyFile(url);
  185. });
  186. };
  187. /**
  188. * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
  189. */
  190. WebSocket.__initialize = function() {
  191. if (WebSocket.__flash) return;
  192. if (WebSocket.__swfLocation) {
  193. // For backword compatibility.
  194. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  195. }
  196. if (!window.WEB_SOCKET_SWF_LOCATION) {
  197. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  198. return;
  199. }
  200. var container = document.createElement("div");
  201. container.id = "webSocketContainer";
  202. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  203. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  204. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  205. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  206. // the best we can do as far as we know now.
  207. container.style.position = "absolute";
  208. if (WebSocket.__isFlashLite()) {
  209. container.style.left = "0px";
  210. container.style.top = "0px";
  211. } else {
  212. container.style.left = "-100px";
  213. container.style.top = "-100px";
  214. }
  215. var holder = document.createElement("div");
  216. holder.id = "webSocketFlash";
  217. container.appendChild(holder);
  218. document.body.appendChild(container);
  219. // See this article for hasPriority:
  220. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  221. swfobject.embedSWF(
  222. WEB_SOCKET_SWF_LOCATION,
  223. "webSocketFlash",
  224. "1" /* width */,
  225. "1" /* height */,
  226. "10.0.0" /* SWF version */,
  227. null,
  228. null,
  229. {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
  230. null,
  231. function(e) {
  232. if (!e.success) {
  233. console.error("[WebSocket] swfobject.embedSWF failed");
  234. }
  235. });
  236. };
  237. /**
  238. * Called by Flash to notify JS that it's fully loaded and ready
  239. * for communication.
  240. */
  241. WebSocket.__onFlashInitialized = function() {
  242. // We need to set a timeout here to avoid round-trip calls
  243. // to flash during the initialization process.
  244. setTimeout(function() {
  245. WebSocket.__flash = document.getElementById("webSocketFlash");
  246. WebSocket.__flash.setCallerUrl(location.href);
  247. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  248. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  249. WebSocket.__tasks[i]();
  250. }
  251. WebSocket.__tasks = [];
  252. }, 0);
  253. };
  254. /**
  255. * Called by Flash to notify WebSockets events are fired.
  256. */
  257. WebSocket.__onFlashEvent = function() {
  258. setTimeout(function() {
  259. try {
  260. // Gets events using receiveEvents() instead of getting it from event object
  261. // of Flash event. This is to make sure to keep message order.
  262. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  263. var events = WebSocket.__flash.receiveEvents();
  264. for (var i = 0; i < events.length; ++i) {
  265. WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
  266. }
  267. } catch (e) {
  268. console.error(e);
  269. }
  270. }, 0);
  271. return true;
  272. };
  273. // Called by Flash.
  274. WebSocket.__log = function(message) {
  275. console.log(decodeURIComponent(message));
  276. };
  277. // Called by Flash.
  278. WebSocket.__error = function(message) {
  279. console.error(decodeURIComponent(message));
  280. };
  281. WebSocket.__addTask = function(task) {
  282. if (WebSocket.__flash) {
  283. task();
  284. } else {
  285. WebSocket.__tasks.push(task);
  286. }
  287. };
  288. /**
  289. * Test if the browser is running flash lite.
  290. * @return {boolean} True if flash lite is running, false otherwise.
  291. */
  292. WebSocket.__isFlashLite = function() {
  293. if (!window.navigator || !window.navigator.mimeTypes) {
  294. return false;
  295. }
  296. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  297. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
  298. return false;
  299. }
  300. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  301. };
  302. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  303. if (window.addEventListener) {
  304. window.addEventListener("load", function(){
  305. WebSocket.__initialize();
  306. }, false);
  307. } else {
  308. window.attachEvent("onload", function(){
  309. WebSocket.__initialize();
  310. });
  311. }
  312. }
  313. })();