web_socket.js 10 KB

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