websock.js 8.6 KB

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