websock.js 9.2 KB

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