web_socket.js 8.8 KB

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