web_socket.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. function hasFlash() {
  10. if ('navigator' in window && 'plugins' in navigator && navigator.plugins['Shockwave Flash']) {
  11. return !!navigator.plugins['Shockwave Flash'].description;
  12. }
  13. if ('ActiveXObject' in window) {
  14. try {
  15. return !!new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  16. } catch (e) {}
  17. }
  18. return false;
  19. }
  20. if (!hasFlash()) {
  21. console.error("Flash Player is not installed.");
  22. return;
  23. }
  24. WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
  25. var self = this;
  26. self.readyState = WebSocket.CONNECTING;
  27. self.bufferedAmount = 0;
  28. WebSocket.__addTask(function() {
  29. self.__flash =
  30. WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
  31. self.__flash.addEventListener("open", function(fe) {
  32. try {
  33. if (self.onopen) self.onopen();
  34. } catch (e) {
  35. console.error(e.toString());
  36. }
  37. });
  38. self.__flash.addEventListener("close", function(fe) {
  39. try {
  40. if (self.onclose) self.onclose();
  41. } catch (e) {
  42. console.error(e.toString());
  43. }
  44. });
  45. self.__flash.addEventListener("message", function(fe) {
  46. var i, arr, data;
  47. arr = self.__flash.readSocketData();
  48. for (i=0; i < arr.length; i++) {
  49. data = decodeURIComponent(arr[i]);
  50. try {
  51. if (self.onmessage) {
  52. var e;
  53. if (window.MessageEvent) {
  54. e = document.createEvent("MessageEvent");
  55. e.initMessageEvent("message", false, false, data, null, null, window, null);
  56. } else { // IE
  57. e = {data: data};
  58. }
  59. self.onmessage(e);
  60. }
  61. } catch (e) {
  62. console.error(e.toString());
  63. }
  64. }
  65. });
  66. self.__flash.addEventListener("error", function(fe) {
  67. try {
  68. if (self.onerror) self.onerror();
  69. } catch (e) {
  70. console.error(e.toString());
  71. }
  72. });
  73. self.__flash.addEventListener("stateChange", function(fe) {
  74. try {
  75. self.readyState = fe.getReadyState();
  76. self.bufferedAmount = fe.getBufferedAmount();
  77. } catch (e) {
  78. console.error(e.toString());
  79. }
  80. });
  81. //console.log("[WebSocket] Flash object is ready");
  82. });
  83. }
  84. WebSocket.prototype.send = function(data) {
  85. if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
  86. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  87. }
  88. var result = this.__flash.send(encodeURIComponent(data));
  89. if (result < 0) { // success
  90. return true;
  91. } else {
  92. this.bufferedAmount = result;
  93. return false;
  94. }
  95. };
  96. WebSocket.prototype.close = function() {
  97. if (!this.__flash) return;
  98. if (this.readyState != WebSocket.OPEN) return;
  99. this.__flash.close();
  100. // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
  101. // which causes weird error:
  102. // > You are trying to call recursively into the Flash Player which is not allowed.
  103. this.readyState = WebSocket.CLOSED;
  104. if (this.onclose) this.onclose();
  105. };
  106. /**
  107. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  108. *
  109. * @param {string} type
  110. * @param {function} listener
  111. * @param {boolean} useCapture !NB Not implemented yet
  112. * @return void
  113. */
  114. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  115. if (!('__events' in this)) {
  116. this.__events = {};
  117. }
  118. if (!(type in this.__events)) {
  119. this.__events[type] = [];
  120. if ('function' == typeof this['on' + type]) {
  121. this.__events[type].defaultHandler = this['on' + type];
  122. this['on' + type] = WebSocket_FireEvent(this, type);
  123. }
  124. }
  125. this.__events[type].push(listener);
  126. };
  127. /**
  128. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  129. *
  130. * @param {string} type
  131. * @param {function} listener
  132. * @param {boolean} useCapture NB! Not implemented yet
  133. * @return void
  134. */
  135. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  136. if (!('__events' in this)) {
  137. this.__events = {};
  138. }
  139. if (!(type in this.__events)) return;
  140. for (var i = this.__events.length; i > -1; --i) {
  141. if (listener === this.__events[type][i]) {
  142. this.__events[type].splice(i, 1);
  143. break;
  144. }
  145. }
  146. };
  147. /**
  148. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  149. *
  150. * @param {WebSocketEvent} event
  151. * @return void
  152. */
  153. WebSocket.prototype.dispatchEvent = function(event) {
  154. if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  155. if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
  156. for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
  157. this.__events[event.type][i](event);
  158. if (event.cancelBubble) break;
  159. }
  160. if (false !== event.returnValue &&
  161. 'function' == typeof this.__events[event.type].defaultHandler)
  162. {
  163. this.__events[event.type].defaultHandler(event);
  164. }
  165. };
  166. /**
  167. *
  168. * @param {object} object
  169. * @param {string} type
  170. */
  171. function WebSocket_FireEvent(object, type) {
  172. return function(data) {
  173. var event = new WebSocketEvent();
  174. event.initEvent(type, true, true);
  175. event.target = event.currentTarget = object;
  176. for (var key in data) {
  177. event[key] = data[key];
  178. }
  179. object.dispatchEvent(event, arguments);
  180. };
  181. }
  182. /**
  183. * Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
  184. *
  185. * @class
  186. * @constructor
  187. */
  188. function WebSocketEvent(){}
  189. /**
  190. *
  191. * @type boolean
  192. */
  193. WebSocketEvent.prototype.cancelable = true;
  194. /**
  195. *
  196. * @type boolean
  197. */
  198. WebSocketEvent.prototype.cancelBubble = false;
  199. /**
  200. *
  201. * @return void
  202. */
  203. WebSocketEvent.prototype.preventDefault = function() {
  204. if (this.cancelable) {
  205. this.returnValue = false;
  206. }
  207. };
  208. /**
  209. *
  210. * @return void
  211. */
  212. WebSocketEvent.prototype.stopPropagation = function() {
  213. this.cancelBubble = true;
  214. };
  215. /**
  216. *
  217. * @param {string} eventTypeArg
  218. * @param {boolean} canBubbleArg
  219. * @param {boolean} cancelableArg
  220. * @return void
  221. */
  222. WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
  223. this.type = eventTypeArg;
  224. this.cancelable = cancelableArg;
  225. this.timeStamp = new Date();
  226. };
  227. WebSocket.CONNECTING = 0;
  228. WebSocket.OPEN = 1;
  229. WebSocket.CLOSING = 2;
  230. WebSocket.CLOSED = 3;
  231. WebSocket.__tasks = [];
  232. WebSocket.__initialize = function(debug) {
  233. if (!WebSocket.__swfLocation) {
  234. console.error("[WebSocket] set WebSocket.__swfLocation to location of WebSocketMain.swf");
  235. return;
  236. }
  237. var container = document.createElement("div");
  238. container.id = "webSocketContainer";
  239. // Puts the Flash out of the window. Note that we cannot use display: none or visibility: hidden
  240. // here because it prevents Flash from loading at least in IE.
  241. container.style.position = "absolute";
  242. container.style.left = "-100px";
  243. container.style.top = "-100px";
  244. var holder = document.createElement("div");
  245. holder.id = "webSocketFlash";
  246. container.appendChild(holder);
  247. document.body.appendChild(container);
  248. swfobject.embedSWF(
  249. WebSocket.__swfLocation, "webSocketFlash", "8", "8", "9.0.0",
  250. null, {bridgeName: "webSocket"}, null, null,
  251. function(e) {
  252. if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
  253. }
  254. );
  255. FABridge.addInitializationCallback("webSocket", function() {
  256. try {
  257. //console.log("[WebSocket] FABridge initializad");
  258. WebSocket.__flash = FABridge.webSocket.root();
  259. WebSocket.__flash.setCallerUrl(location.href);
  260. if (typeof debug !== "undefined") {
  261. WebSocket.__flash.setDebug(debug);
  262. }
  263. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  264. WebSocket.__tasks[i]();
  265. }
  266. WebSocket.__tasks = [];
  267. } catch (e) {
  268. console.error("[WebSocket] " + e.toString());
  269. }
  270. });
  271. };
  272. WebSocket.__addTask = function(task) {
  273. if (WebSocket.__flash) {
  274. task();
  275. } else {
  276. WebSocket.__tasks.push(task);
  277. }
  278. }
  279. // called from Flash
  280. window.webSocketLog = function(message) {
  281. console.log(decodeURIComponent(message));
  282. };
  283. // called from Flash
  284. window.webSocketError = function(message) {
  285. console.error(decodeURIComponent(message));
  286. };
  287. /*
  288. if (window.addEventListener) {
  289. window.addEventListener("load", WebSocket.__initialize, false);
  290. } else {
  291. window.attachEvent("onload", WebSocket.__initialize);
  292. }
  293. */
  294. })();