websock.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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";
  31. extra += start + "web-socket-js/swfobject.js" + end;
  32. extra += start + "web-socket-js/FABridge.js" + end;
  33. extra += start + "web-socket-js/web_socket.js" + end;
  34. document.write(extra);
  35. }());
  36. }
  37. function Websock() {
  38. var api = {}, // Public API
  39. websocket = null, // WebSocket object
  40. rQ = [], // Receive queue
  41. rQi = 0, // Receive queue index
  42. rQmax = 10000, // Max receive queue size before compacting
  43. sQ = [], // Send queue
  44. eventHandlers = {
  45. 'message' : function() {},
  46. 'open' : function() {},
  47. 'close' : function() {},
  48. 'error' : function() {}
  49. };
  50. //
  51. // Queue public functions
  52. //
  53. function get_sQ() {
  54. return sQ;
  55. }
  56. function get_rQ() {
  57. return rQ;
  58. }
  59. function get_rQi() {
  60. return rQi;
  61. }
  62. set_rQi = function(val) {
  63. rQi = val;
  64. }
  65. function rQlen() {
  66. return rQ.length - rQi;
  67. }
  68. function rQpeek8() {
  69. return (rQ[rQi] );
  70. }
  71. function rQshift8() {
  72. return (rQ[rQi++] );
  73. }
  74. function rQunshift8(num) {
  75. if (rQi === 0) {
  76. rQ.unshift(num);
  77. } else {
  78. rQi -= 1;
  79. rQ[rQi] = num;
  80. }
  81. }
  82. function rQshift16() {
  83. return (rQ[rQi++] << 8) +
  84. (rQ[rQi++] );
  85. }
  86. function rQshift32() {
  87. return (rQ[rQi++] << 24) +
  88. (rQ[rQi++] << 16) +
  89. (rQ[rQi++] << 8) +
  90. (rQ[rQi++] );
  91. }
  92. function rQshiftStr(len) {
  93. var arr = rQ.slice(rQi, rQi + len);
  94. rQi += len;
  95. return arr.map(function (num) {
  96. return String.fromCharCode(num); } ).join('');
  97. }
  98. function rQshiftBytes(len) {
  99. rQi += len;
  100. return rQ.slice(rQi-len, rQi);
  101. }
  102. function rQslice(start, end) {
  103. if (end) {
  104. return rQ.slice(rQi + start, rQi + end);
  105. } else {
  106. return rQ.slice(rQi + start);
  107. }
  108. }
  109. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  110. // to be available in the receive queue. Return true if we need to
  111. // wait (and possibly print a debug message), otherwise false.
  112. function rQwait(msg, num, goback) {
  113. var rQlen = rQ.length - rQi; // Skip rQlen() function call
  114. if (rQlen < num) {
  115. if (goback) {
  116. if (rQi < goback) {
  117. throw("rQwait cannot backup " + goback + " bytes");
  118. }
  119. rQi -= goback;
  120. }
  121. //Util.Debug(" waiting for " + (num-rQlen) +
  122. // " " + msg + " byte(s)");
  123. return true; // true means need more data
  124. }
  125. return false;
  126. }
  127. //
  128. // Private utility routines
  129. //
  130. function encode_message() {
  131. /* base64 encode */
  132. return Base64.encode(sQ);
  133. }
  134. function decode_message(data) {
  135. //Util.Debug(">> decode_message: " + data);
  136. /* base64 decode */
  137. rQ = rQ.concat(Base64.decode(data, 0));
  138. //Util.Debug(">> decode_message, rQ: " + rQ);
  139. }
  140. //
  141. // Public Send functions
  142. //
  143. function flush() {
  144. if (websocket.bufferedAmount === 0) {
  145. //Util.Debug("arr: " + arr);
  146. //Util.Debug("sQ: " + sQ);
  147. if (sQ) {
  148. websocket.send(encode_message(sQ));
  149. sQ = [];
  150. }
  151. return true;
  152. } else {
  153. Util.Debug("Delaying send");
  154. return false;
  155. }
  156. }
  157. // overridable for testing
  158. function send(arr) {
  159. //Util.Debug(">> send_array: " + arr);
  160. sQ = sQ.concat(arr);
  161. flush();
  162. };
  163. function send_string(str) {
  164. //Util.Debug(">> send_string: " + str);
  165. api.send(str.split('').map(
  166. function (chr) { return chr.charCodeAt(0); } ) );
  167. }
  168. //
  169. // Other public functions
  170. function recv_message(e) {
  171. //Util.Debug(">> recv_message: " + e.data.length);
  172. try {
  173. decode_message(e.data);
  174. if (rQlen() > 0) {
  175. eventHandlers['message']();
  176. // Compact the receive queue
  177. if (rQ.length > rQmax) {
  178. //Util.Debug("Compacting receive queue");
  179. rQ = rQ.slice(rQi);
  180. rQi = 0;
  181. }
  182. } else {
  183. Util.Debug("Ignoring empty message");
  184. }
  185. } catch (exc) {
  186. if (typeof exc.stack !== 'undefined') {
  187. Util.Warn("recv_message, caught exception: " + exc.stack);
  188. } else if (typeof exc.description !== 'undefined') {
  189. Util.Warn("recv_message, caught exception: " + exc.description);
  190. } else {
  191. Util.Warn("recv_message, caught exception:" + exc);
  192. }
  193. if (typeof exc.name !== 'undefined') {
  194. eventHandlers['error'](exc.name + ": " + exc.message);
  195. } else {
  196. eventHandlers['error'](exc);
  197. }
  198. }
  199. //Util.Debug("<< recv_message");
  200. };
  201. // Set event handlers
  202. function on(evt, handler) {
  203. eventHandlers[evt] = handler;
  204. }
  205. function init() {
  206. rQ = [];
  207. rQi = 0;
  208. sQ = [];
  209. websocket = null;
  210. }
  211. function open(uri) {
  212. init();
  213. websocket = new WebSocket(uri);
  214. websocket.onmessage = recv_message;
  215. websocket.onopen = function(e) {
  216. Util.Debug(">> WebSock.onopen");
  217. eventHandlers['open']();
  218. Util.Debug("<< WebSock.onopen");
  219. }
  220. websocket.onclose = function(e) {
  221. Util.Debug(">> WebSock.onclose");
  222. eventHandlers['close']();
  223. Util.Debug("<< WebSock.onclose");
  224. }
  225. websocket.onerror = function(e) {
  226. Util.Debug("<< WebSock.onerror: " + e);
  227. eventHandlers['error'](e);
  228. Util.Debug("<< WebSock.onerror: ");
  229. }
  230. }
  231. function close() {
  232. if (websocket) {
  233. if ((websocket.readyState === WebSocket.OPEN) ||
  234. (websocket.readyState === WebSocket.CONNECTING)) {
  235. Util.Info("Closing WebSocket connection");
  236. websocket.close();
  237. }
  238. websocket.onmessage = function (e) { return; };
  239. }
  240. }
  241. function constructor() {
  242. // Direct access to send and receive queues
  243. api.get_sQ = get_sQ;
  244. api.get_rQ = get_rQ;
  245. api.get_rQi = get_rQi;
  246. api.set_rQi = set_rQi;
  247. // Routines to read from the receive queue
  248. api.rQlen = rQlen;
  249. api.rQpeek8 = rQpeek8;
  250. api.rQshift8 = rQshift8;
  251. api.rQunshift8 = rQunshift8;
  252. api.rQshift16 = rQshift16;
  253. api.rQshift32 = rQshift32;
  254. api.rQshiftStr = rQshiftStr;
  255. api.rQshiftBytes = rQshiftBytes;
  256. api.rQslice = rQslice;
  257. api.rQwait = rQwait;
  258. api.flush = flush;
  259. api.send = send;
  260. api.send_string = send_string;
  261. api.recv_message = recv_message;
  262. api.on = on;
  263. api.init = init;
  264. api.open = open;
  265. api.close = close;
  266. return api;
  267. }
  268. return constructor();
  269. }