websock.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*
  2. * Websock: high-performance binary WebSockets
  3. * Copyright (C) 2011 Joel Martin
  4. * Licensed under LGPL-3 (see LICENSE.txt)
  5. *
  6. * Websock is similar to the standard WebSocket object but Websock
  7. * enables communication with raw TCP sockets (i.e. the binary stream)
  8. * via websockify. This is accomplished by base64 encoding the data
  9. * stream between Websock and websockify.
  10. *
  11. * Websock has built-in receive queue buffering; the message event
  12. * does not contain actual data but is simply a notification that
  13. * there is new data available. Several rQ* methods are available to
  14. * read binary data off of the receive queue.
  15. */
  16. // Load Flash WebSocket emulator if needed
  17. if (window.WebSocket) {
  18. Websock_native = true;
  19. } else {
  20. /* no builtin WebSocket so load web_socket.js */
  21. Websock_native = false;
  22. (function () {
  23. function get_INCLUDE_URI() {
  24. return (typeof INCLUDE_URI !== "undefined") ?
  25. INCLUDE_URI : "include/";
  26. }
  27. var start = "<script src='" + get_INCLUDE_URI(),
  28. end = "'><\/script>", extra = "";
  29. WEB_SOCKET_SWF_LOCATION = get_INCLUDE_URI() +
  30. "web-socket-js/WebSocketMain.swf?" + Math.random();
  31. if (Util.Engine.trident) {
  32. Util.Debug("Forcing uncached load of WebSocketMain.swf");
  33. WEB_SOCKET_SWF_LOCATION += "?" + Math.random();
  34. }
  35. extra += start + "web-socket-js/swfobject.js" + end;
  36. extra += start + "web-socket-js/FABridge.js" + end;
  37. extra += start + "web-socket-js/web_socket.js" + end;
  38. document.write(extra);
  39. }());
  40. }
  41. function Websock() {
  42. var api = {}, // Public API
  43. websocket = null, // WebSocket object
  44. rQ = [], // Receive queue
  45. rQi = 0, // Receive queue index
  46. rQmax = 10000, // Max receive queue size before compacting
  47. sQ = [], // Send queue
  48. eventHandlers = {
  49. 'message' : function() {},
  50. 'open' : function() {},
  51. 'close' : function() {},
  52. 'error' : function() {}
  53. };
  54. //
  55. // Queue public functions
  56. //
  57. function get_sQ() {
  58. return sQ;
  59. }
  60. function get_rQ() {
  61. return rQ;
  62. }
  63. function get_rQi() {
  64. return rQi;
  65. }
  66. set_rQi = function(val) {
  67. rQi = val;
  68. }
  69. function rQlen() {
  70. return rQ.length - rQi;
  71. }
  72. function rQpeek8() {
  73. return (rQ[rQi] );
  74. }
  75. function rQshift8() {
  76. return (rQ[rQi++] );
  77. }
  78. function rQunshift8(num) {
  79. if (rQi === 0) {
  80. rQ.unshift(num);
  81. } else {
  82. rQi -= 1;
  83. rQ[rQi] = num;
  84. }
  85. }
  86. function rQshift16() {
  87. return (rQ[rQi++] << 8) +
  88. (rQ[rQi++] );
  89. }
  90. function rQshift32() {
  91. return (rQ[rQi++] << 24) +
  92. (rQ[rQi++] << 16) +
  93. (rQ[rQi++] << 8) +
  94. (rQ[rQi++] );
  95. }
  96. function rQshiftStr(len) {
  97. var arr = rQ.slice(rQi, rQi + len);
  98. rQi += len;
  99. return arr.map(function (num) {
  100. return String.fromCharCode(num); } ).join('');
  101. }
  102. function rQshiftBytes(len) {
  103. rQi += len;
  104. return rQ.slice(rQi-len, rQi);
  105. }
  106. function rQslice(start, end) {
  107. if (end) {
  108. return rQ.slice(rQi + start, rQi + end);
  109. } else {
  110. return rQ.slice(rQi + start);
  111. }
  112. }
  113. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  114. // to be available in the receive queue. Return true if we need to
  115. // wait (and possibly print a debug message), otherwise false.
  116. function rQwait(msg, num, goback) {
  117. var rQlen = rQ.length - rQi; // Skip rQlen() function call
  118. if (rQlen < num) {
  119. if (goback) {
  120. if (rQi < goback) {
  121. throw("rQwait cannot backup " + goback + " bytes");
  122. }
  123. rQi -= goback;
  124. }
  125. //Util.Debug(" waiting for " + (num-rQlen) +
  126. // " " + msg + " byte(s)");
  127. return true; // true means need more data
  128. }
  129. return false;
  130. }
  131. //
  132. // Private utility routines
  133. //
  134. function encode_message() {
  135. /* base64 encode */
  136. return Base64.encode(sQ);
  137. }
  138. function decode_message(data) {
  139. //Util.Debug(">> decode_message: " + data);
  140. /* base64 decode */
  141. rQ = rQ.concat(Base64.decode(data, 0));
  142. //Util.Debug(">> decode_message, rQ: " + rQ);
  143. }
  144. //
  145. // Public Send functions
  146. //
  147. function flush() {
  148. if (websocket.bufferedAmount !== 0) {
  149. Util.Debug("bufferedAmount: " + websocket.bufferedAmount);
  150. }
  151. if (websocket.bufferedAmount < api.maxBufferedAmount) {
  152. //Util.Debug("arr: " + arr);
  153. //Util.Debug("sQ: " + sQ);
  154. if (sQ) {
  155. websocket.send(encode_message(sQ));
  156. sQ = [];
  157. }
  158. return true;
  159. } else {
  160. Util.Info("Delaying send, bufferedAmount: " +
  161. websocket.bufferedAmount);
  162. return false;
  163. }
  164. }
  165. // overridable for testing
  166. function send(arr) {
  167. //Util.Debug(">> send_array: " + arr);
  168. sQ = sQ.concat(arr);
  169. return flush();
  170. };
  171. function send_string(str) {
  172. //Util.Debug(">> send_string: " + str);
  173. api.send(str.split('').map(
  174. function (chr) { return chr.charCodeAt(0); } ) );
  175. }
  176. //
  177. // Other public functions
  178. function recv_message(e) {
  179. //Util.Debug(">> recv_message: " + e.data.length);
  180. try {
  181. decode_message(e.data);
  182. if (rQlen() > 0) {
  183. eventHandlers['message']();
  184. // Compact the receive queue
  185. if (rQ.length > rQmax) {
  186. //Util.Debug("Compacting receive queue");
  187. rQ = rQ.slice(rQi);
  188. rQi = 0;
  189. }
  190. } else {
  191. Util.Debug("Ignoring empty message");
  192. }
  193. } catch (exc) {
  194. if (typeof exc.stack !== 'undefined') {
  195. Util.Warn("recv_message, caught exception: " + exc.stack);
  196. } else if (typeof exc.description !== 'undefined') {
  197. Util.Warn("recv_message, caught exception: " + exc.description);
  198. } else {
  199. Util.Warn("recv_message, caught exception:" + exc);
  200. }
  201. if (typeof exc.name !== 'undefined') {
  202. eventHandlers['error'](exc.name + ": " + exc.message);
  203. } else {
  204. eventHandlers['error'](exc);
  205. }
  206. }
  207. //Util.Debug("<< recv_message");
  208. };
  209. // Set event handlers
  210. function on(evt, handler) {
  211. eventHandlers[evt] = handler;
  212. }
  213. function init() {
  214. rQ = [];
  215. rQi = 0;
  216. sQ = [];
  217. websocket = null;
  218. }
  219. function open(uri) {
  220. init();
  221. websocket = new WebSocket(uri);
  222. websocket.onmessage = recv_message;
  223. websocket.onopen = function(e) {
  224. Util.Debug(">> WebSock.onopen");
  225. eventHandlers['open']();
  226. Util.Debug("<< WebSock.onopen");
  227. }
  228. websocket.onclose = function(e) {
  229. Util.Debug(">> WebSock.onclose");
  230. eventHandlers['close']();
  231. Util.Debug("<< WebSock.onclose");
  232. }
  233. websocket.onerror = function(e) {
  234. Util.Debug("<< WebSock.onerror: " + e);
  235. eventHandlers['error'](e);
  236. Util.Debug("<< WebSock.onerror: ");
  237. }
  238. }
  239. function close() {
  240. if (websocket) {
  241. if ((websocket.readyState === WebSocket.OPEN) ||
  242. (websocket.readyState === WebSocket.CONNECTING)) {
  243. Util.Info("Closing WebSocket connection");
  244. websocket.close();
  245. }
  246. websocket.onmessage = function (e) { return; };
  247. }
  248. }
  249. function constructor() {
  250. // Configuration settings
  251. api.maxBufferedAmount = 200;
  252. // Direct access to send and receive queues
  253. api.get_sQ = get_sQ;
  254. api.get_rQ = get_rQ;
  255. api.get_rQi = get_rQi;
  256. api.set_rQi = set_rQi;
  257. // Routines to read from the receive queue
  258. api.rQlen = rQlen;
  259. api.rQpeek8 = rQpeek8;
  260. api.rQshift8 = rQshift8;
  261. api.rQunshift8 = rQunshift8;
  262. api.rQshift16 = rQshift16;
  263. api.rQshift32 = rQshift32;
  264. api.rQshiftStr = rQshiftStr;
  265. api.rQshiftBytes = rQshiftBytes;
  266. api.rQslice = rQslice;
  267. api.rQwait = rQwait;
  268. api.flush = flush;
  269. api.send = send;
  270. api.send_string = send_string;
  271. api.recv_message = recv_message;
  272. api.on = on;
  273. api.init = init;
  274. api.open = open;
  275. api.close = close;
  276. return api;
  277. }
  278. return constructor();
  279. }