websock.js 9.0 KB

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