web_socket.js 9.2 KB

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