websock.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * Websock: high-performance binary WebSockets
  3. * Copyright (C) 2012 Joel Martin
  4. * Licensed under MPL 2.0 (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. window.WEB_SOCKET_SWF_LOCATION = Util.get_include_uri() +
  33. "web-socket-js/WebSocketMain.swf";
  34. if (Util.Engine.trident) {
  35. Util.Debug("Forcing uncached load of WebSocketMain.swf");
  36. window.WEB_SOCKET_SWF_LOCATION += "?" + Math.random();
  37. }
  38. Util.load_scripts(["web-socket-js/swfobject.js",
  39. "web-socket-js/web_socket.js"]);
  40. }());
  41. }
  42. function Websock() {
  43. "use strict";
  44. var api = {}, // Public API
  45. websocket = null, // WebSocket object
  46. mode = 'base64', // Current WebSocket mode: 'binary', 'base64'
  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. if (typeof(len) === 'undefined') { len = rQlen(); }
  102. var arr = rQ.slice(rQi, rQi + len);
  103. rQi += len;
  104. return String.fromCharCode.apply(null, arr);
  105. }
  106. function rQshiftBytes(len) {
  107. if (typeof(len) === 'undefined') { len = rQlen(); }
  108. rQi += len;
  109. return rQ.slice(rQi-len, rQi);
  110. }
  111. function rQslice(start, end) {
  112. if (end) {
  113. return rQ.slice(rQi + start, rQi + end);
  114. } else {
  115. return rQ.slice(rQi + start);
  116. }
  117. }
  118. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  119. // to be available in the receive queue. Return true if we need to
  120. // wait (and possibly print a debug message), otherwise false.
  121. function rQwait(msg, num, goback) {
  122. var rQlen = rQ.length - rQi; // Skip rQlen() function call
  123. if (rQlen < num) {
  124. if (goback) {
  125. if (rQi < goback) {
  126. throw("rQwait cannot backup " + goback + " bytes");
  127. }
  128. rQi -= goback;
  129. }
  130. //Util.Debug(" waiting for " + (num-rQlen) +
  131. // " " + msg + " byte(s)");
  132. return true; // true means need more data
  133. }
  134. return false;
  135. }
  136. //
  137. // Private utility routines
  138. //
  139. function encode_message() {
  140. if (mode === 'binary') {
  141. // Put in a binary arraybuffer
  142. return (new Uint8Array(sQ)).buffer;
  143. } else {
  144. // base64 encode
  145. return Base64.encode(sQ);
  146. }
  147. }
  148. function decode_message(data) {
  149. //Util.Debug(">> decode_message: " + data);
  150. if (mode === 'binary') {
  151. // push arraybuffer values onto the end
  152. var u8 = new Uint8Array(data);
  153. for (var i = 0; i < u8.length; i++) {
  154. rQ.push(u8[i]);
  155. }
  156. } else {
  157. // base64 decode and concat to the end
  158. rQ = rQ.concat(Base64.decode(data, 0));
  159. }
  160. //Util.Debug(">> decode_message, rQ: " + rQ);
  161. }
  162. //
  163. // Public Send functions
  164. //
  165. function flush() {
  166. if (websocket.bufferedAmount !== 0) {
  167. Util.Debug("bufferedAmount: " + websocket.bufferedAmount);
  168. }
  169. if (websocket.bufferedAmount < api.maxBufferedAmount) {
  170. //Util.Debug("arr: " + arr);
  171. //Util.Debug("sQ: " + sQ);
  172. if (sQ.length > 0) {
  173. websocket.send(encode_message(sQ));
  174. sQ = [];
  175. }
  176. return true;
  177. } else {
  178. Util.Info("Delaying send, bufferedAmount: " +
  179. websocket.bufferedAmount);
  180. return false;
  181. }
  182. }
  183. // overridable for testing
  184. function send(arr) {
  185. //Util.Debug(">> send_array: " + arr);
  186. sQ = sQ.concat(arr);
  187. return flush();
  188. }
  189. function send_string(str) {
  190. //Util.Debug(">> send_string: " + str);
  191. api.send(str.split('').map(
  192. function (chr) { return chr.charCodeAt(0); } ) );
  193. }
  194. //
  195. // Other public functions
  196. function recv_message(e) {
  197. //Util.Debug(">> recv_message: " + e.data.length);
  198. try {
  199. decode_message(e.data);
  200. if (rQlen() > 0) {
  201. eventHandlers.message();
  202. // Compact the receive queue
  203. if (rQ.length > rQmax) {
  204. //Util.Debug("Compacting receive queue");
  205. rQ = rQ.slice(rQi);
  206. rQi = 0;
  207. }
  208. } else {
  209. Util.Debug("Ignoring empty message");
  210. }
  211. } catch (exc) {
  212. if (typeof exc.stack !== 'undefined') {
  213. Util.Warn("recv_message, caught exception: " + exc.stack);
  214. } else if (typeof exc.description !== 'undefined') {
  215. Util.Warn("recv_message, caught exception: " + exc.description);
  216. } else {
  217. Util.Warn("recv_message, caught exception:" + exc);
  218. }
  219. if (typeof exc.name !== 'undefined') {
  220. eventHandlers.error(exc.name + ": " + exc.message);
  221. } else {
  222. eventHandlers.error(exc);
  223. }
  224. }
  225. //Util.Debug("<< recv_message");
  226. }
  227. // Set event handlers
  228. function on(evt, handler) {
  229. eventHandlers[evt] = handler;
  230. }
  231. function init(protocols) {
  232. rQ = [];
  233. rQi = 0;
  234. sQ = [];
  235. websocket = null;
  236. var bt = false,
  237. wsbt = false,
  238. try_binary = false;
  239. // Check for full typed array support
  240. if (('Uint8Array' in window) &&
  241. ('set' in Uint8Array.prototype)) {
  242. bt = true;
  243. }
  244. // Check for full binary type support in WebSockets
  245. // TODO: this sucks, the property should exist on the prototype
  246. // but it does not.
  247. try {
  248. if (bt && ('binaryType' in (new WebSocket("ws://localhost:17523")))) {
  249. Util.Info("Detected binaryType support in WebSockets");
  250. wsbt = true;
  251. }
  252. } catch (exc) {
  253. // Just ignore failed test localhost connections
  254. }
  255. // Default protocols if not specified
  256. if (typeof(protocols) === "undefined") {
  257. if (wsbt) {
  258. protocols = ['binary', 'base64'];
  259. } else {
  260. protocols = 'base64';
  261. }
  262. }
  263. // If no binary support, make sure it was not requested
  264. if (!wsbt) {
  265. if (protocols === 'binary') {
  266. throw("WebSocket binary sub-protocol requested but not supported");
  267. }
  268. if (typeof(protocols) === "object") {
  269. var new_protocols = [];
  270. for (var i = 0; i < protocols.length; i++) {
  271. if (protocols[i] === 'binary') {
  272. Util.Error("Skipping unsupported WebSocket binary sub-protocol");
  273. } else {
  274. new_protocols.push(protocols[i]);
  275. }
  276. }
  277. if (new_protocols.length > 0) {
  278. protocols = new_protocols;
  279. } else {
  280. throw("Only WebSocket binary sub-protocol was requested and not supported.");
  281. }
  282. }
  283. }
  284. return protocols;
  285. }
  286. function open(uri, protocols) {
  287. protocols = init(protocols);
  288. if (test_mode) {
  289. websocket = {};
  290. } else {
  291. websocket = new WebSocket(uri, protocols);
  292. }
  293. websocket.onmessage = recv_message;
  294. websocket.onopen = function() {
  295. Util.Debug(">> WebSock.onopen");
  296. if (websocket.protocol) {
  297. mode = websocket.protocol;
  298. Util.Info("Server chose sub-protocol: " + websocket.protocol);
  299. } else {
  300. mode = 'base64';
  301. Util.Error("Server select no sub-protocol!: " + websocket.protocol);
  302. }
  303. if (mode === 'binary') {
  304. websocket.binaryType = 'arraybuffer';
  305. }
  306. eventHandlers.open();
  307. Util.Debug("<< WebSock.onopen");
  308. };
  309. websocket.onclose = function(e) {
  310. Util.Debug(">> WebSock.onclose");
  311. eventHandlers.close(e);
  312. Util.Debug("<< WebSock.onclose");
  313. };
  314. websocket.onerror = function(e) {
  315. Util.Debug(">> WebSock.onerror: " + e);
  316. eventHandlers.error(e);
  317. Util.Debug("<< WebSock.onerror");
  318. };
  319. }
  320. function close() {
  321. if (websocket) {
  322. if ((websocket.readyState === WebSocket.OPEN) ||
  323. (websocket.readyState === WebSocket.CONNECTING)) {
  324. Util.Info("Closing WebSocket connection");
  325. websocket.close();
  326. }
  327. websocket.onmessage = function (e) { return; };
  328. }
  329. }
  330. // Override internal functions for testing
  331. // Takes a send function, returns reference to recv function
  332. function testMode(override_send, data_mode) {
  333. test_mode = true;
  334. mode = data_mode;
  335. api.send = override_send;
  336. api.close = function () {};
  337. return recv_message;
  338. }
  339. function constructor() {
  340. // Configuration settings
  341. api.maxBufferedAmount = 200;
  342. // Direct access to send and receive queues
  343. api.get_sQ = get_sQ;
  344. api.get_rQ = get_rQ;
  345. api.get_rQi = get_rQi;
  346. api.set_rQi = set_rQi;
  347. // Routines to read from the receive queue
  348. api.rQlen = rQlen;
  349. api.rQpeek8 = rQpeek8;
  350. api.rQshift8 = rQshift8;
  351. api.rQunshift8 = rQunshift8;
  352. api.rQshift16 = rQshift16;
  353. api.rQshift32 = rQshift32;
  354. api.rQshiftStr = rQshiftStr;
  355. api.rQshiftBytes = rQshiftBytes;
  356. api.rQslice = rQslice;
  357. api.rQwait = rQwait;
  358. api.flush = flush;
  359. api.send = send;
  360. api.send_string = send_string;
  361. api.on = on;
  362. api.init = init;
  363. api.open = open;
  364. api.close = close;
  365. api.testMode = testMode;
  366. return api;
  367. }
  368. return constructor();
  369. }