]>
git.proxmox.com Git - mirror_novnc.git/blob - include/websock.js
2 * Websock: high-performance binary WebSockets
3 * Copyright (C) 2012 Joel Martin
4 * Licensed under LGPL-3 (see LICENSE.txt)
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.
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.
17 /*jslint browser: true, bitwise: false, plusplus: false */
18 /*global Util, Base64 */
21 // Load Flash WebSocket emulator if needed
23 // To force WebSocket emulator even when native WebSocket available
24 //window.WEB_SOCKET_FORCE_FLASH = true;
25 // To enable WebSocket emulator debug:
26 //window.WEB_SOCKET_DEBUG=1;
28 if (window
.WebSocket
&& !window
.WEB_SOCKET_FORCE_FLASH
) {
29 Websock_native
= true;
30 } else if (window
.MozWebSocket
&& !window
.WEB_SOCKET_FORCE_FLASH
) {
31 Websock_native
= true;
32 window
.WebSocket
= window
.MozWebSocket
;
34 /* no builtin WebSocket so load web_socket.js */
36 Websock_native
= false;
38 function get_INCLUDE_URI() {
39 return (typeof INCLUDE_URI
!== "undefined") ?
40 INCLUDE_URI
: "include/";
43 var start
= "<script src='" + get_INCLUDE_URI(),
44 end
= "'><\/script>", extra
= "";
46 window
.WEB_SOCKET_SWF_LOCATION
= get_INCLUDE_URI() +
47 "web-socket-js/WebSocketMain.swf";
48 if (Util
.Engine
.trident
) {
49 Util
.Debug("Forcing uncached load of WebSocketMain.swf");
50 window
.WEB_SOCKET_SWF_LOCATION
+= "?" + Math
.random();
52 extra
+= start
+ "web-socket-js/swfobject.js" + end
;
53 extra
+= start
+ "web-socket-js/web_socket.js" + end
;
54 document
.write(extra
);
62 var api
= {}, // Public API
63 websocket
= null, // WebSocket object
64 protocols
, // Protocols to request in priority order
66 rQ
= [], // Receive queue
67 rQi
= 0, // Receive queue index
68 rQmax
= 10000, // Max receive queue size before compacting
69 sQ
= [], // Send queue
72 'message' : function() {},
73 'open' : function() {},
74 'close' : function() {},
75 'error' : function() {}
82 // Queue public functions
95 function set_rQi(val
) {
100 return rQ
.length
- rQi
;
106 function rQshift8() {
109 function rQunshift8(num
) {
118 function rQshift16() {
119 return (rQ
[rQi
++] << 8) +
122 function rQshift32() {
123 return (rQ
[rQi
++] << 24) +
128 function rQslice(start
, end
) {
129 if (mode
=== 'binary') {
131 return rQ
.subarray(rQi
+ start
, rQi
+ end
);
133 return rQ
.subarray(rQi
+ start
);
137 return rQ
.slice(rQi
+ start
, rQi
+ end
);
139 return rQ
.slice(rQi
+ start
);
144 function rQshiftStr(len
) {
145 if (typeof(len
) === 'undefined') { len
= rQlen(); }
146 var arr
= rQslice(0, len
);
148 return String
.fromCharCode
.apply(null, arr
);
150 function rQshiftBytes(len
) {
151 if (typeof(len
) === 'undefined') { len
= rQlen(); }
152 var a
= rQslice(0, len
), b
= [];
153 if (mode
=== 'binary') {
154 // Convert to plain array
157 // Already plain array, just return the original
163 function rQshiftArray(len
) {
164 if (typeof(len
) === 'undefined') { len
= rQlen(); }
165 var a
= rQslice(0, len
);
170 // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
171 // to be available in the receive queue. Return true if we need to
172 // wait (and possibly print a debug message), otherwise false.
173 function rQwait(msg
, num
, goback
) {
174 var rQlen
= rQ
.length
- rQi
; // Skip rQlen() function call
178 throw("rQwait cannot backup " + goback
+ " bytes");
182 //Util.Debug(" waiting for " + (num-rQlen) +
183 // " " + msg + " byte(s)");
184 return true; // true means need more data
190 // Private utility routines
193 function encode_message() {
195 if (mode
=== 'binary') {
196 return (new Uint8Array(sQ
)).buffer
;
198 return Base64
.encode(sQ
);
202 function decode_message(data
) {
203 //Util.Debug(">> decode_message: " + data);
204 if (mode
=== 'binary') {
205 // Create new arraybuffer and dump old and new data into it
206 // TODO: this could be far more efficient and re-use the array
207 var new_rQ
= new Uint8Array(rQ
.length
+ data
.byteLength
);
209 new_rQ
.set(new Uint8Array(data
), rQ
.length
);
212 /* base64 decode and concat to the end */
213 rQ
= rQ
.concat(Base64
.decode(data
, 0));
215 //Util.Debug(">> decode_message, rQ: " + rQ);
220 // Public Send functions
224 if (websocket
.bufferedAmount
!== 0) {
225 Util
.Debug("bufferedAmount: " + websocket
.bufferedAmount
);
227 if (websocket
.bufferedAmount
< api
.maxBufferedAmount
) {
228 //Util.Debug("arr: " + arr);
229 //Util.Debug("sQ: " + sQ);
231 websocket
.send(encode_message(sQ
));
236 Util
.Info("Delaying send, bufferedAmount: " +
237 websocket
.bufferedAmount
);
242 // overridable for testing
244 //Util.Debug(">> send_array: " + arr);
249 function send_string(str
) {
250 //Util.Debug(">> send_string: " + str);
251 api
.send(str
.split('').map(
252 function (chr
) { return chr
.charCodeAt(0); } ) );
256 // Other public functions
258 function recv_message(e
) {
259 //Util.Debug(">> recv_message: " + e.data.length);
262 decode_message(e
.data
);
264 eventHandlers
.message();
265 // Compact the receive queue
266 if (rQ
.length
> rQmax
) {
267 //Util.Debug("Compacting receive queue");
272 Util
.Debug("Ignoring empty message");
275 if (typeof exc
.stack
!== 'undefined') {
276 Util
.Warn("recv_message, caught exception: " + exc
.stack
);
277 } else if (typeof exc
.description
!== 'undefined') {
278 Util
.Warn("recv_message, caught exception: " + exc
.description
);
280 Util
.Warn("recv_message, caught exception:" + exc
);
282 if (typeof exc
.name
!== 'undefined') {
283 eventHandlers
.error(exc
.name
+ ": " + exc
.message
);
285 eventHandlers
.error(exc
);
288 //Util.Debug("<< recv_message");
292 // Set event handlers
293 function on(evt
, handler
) {
294 eventHandlers
[evt
] = handler
;
302 protocols
= "base64";
307 if (('Uint8Array' in window
) &&
308 ('set' in Uint8Array
.prototype)) {
311 // TODO: this sucks, the property should exist on the prototype
314 if (bt
&& ('binaryType' in (new WebSocket("ws://localhost:17523")))) {
318 // Just ignore failed test localhost connections
321 Util
.Info("Detected binaryType support in WebSockets");
322 protocols
= ['binary', 'base64'];
324 Util
.Info("No binaryType support in WebSockets, using base64 encoding");
325 protocols
= 'base64';
335 websocket
= new WebSocket(uri
, protocols
);
338 websocket
.onmessage
= recv_message
;
339 websocket
.onopen = function() {
340 Util
.Debug(">> WebSock.onopen");
341 if (websocket
.protocol
) {
342 mode
= websocket
.protocol
;
343 Util
.Info("Server chose sub-protocol: " + websocket
.protocol
);
346 Util
.Error("Server select no sub-protocol!: " + websocket
.protocol
);
348 if (mode
=== 'binary') {
349 websocket
.binaryType
= 'arraybuffer';
351 eventHandlers
.open();
352 Util
.Debug("<< WebSock.onopen");
354 websocket
.onclose = function(e
) {
355 Util
.Debug(">> WebSock.onclose");
356 eventHandlers
.close(e
);
357 Util
.Debug("<< WebSock.onclose");
359 websocket
.onerror = function(e
) {
360 Util
.Debug(">> WebSock.onerror: " + e
);
361 eventHandlers
.error(e
);
362 Util
.Debug("<< WebSock.onerror");
368 if ((websocket
.readyState
=== WebSocket
.OPEN
) ||
369 (websocket
.readyState
=== WebSocket
.CONNECTING
)) {
370 Util
.Info("Closing WebSocket connection");
373 websocket
.onmessage = function (e
) { return; };
377 // Override internal functions for testing
378 // Takes a send function, returns reference to recv function
379 function testMode(override_send
) {
381 api
.send
= override_send
;
382 api
.close = function () {};
386 function constructor() {
387 // Configuration settings
388 api
.maxBufferedAmount
= 200;
390 // Direct access to send and receive queues
393 api
.get_rQi
= get_rQi
;
394 api
.set_rQi
= set_rQi
;
396 // Routines to read from the receive queue
398 api
.rQpeek8
= rQpeek8
;
399 api
.rQshift8
= rQshift8
;
400 api
.rQunshift8
= rQunshift8
;
401 api
.rQshift16
= rQshift16
;
402 api
.rQshift32
= rQshift32
;
403 api
.rQshiftStr
= rQshiftStr
;
404 api
.rQshiftBytes
= rQshiftBytes
;
405 api
.rQslice
= rQslice
;
410 api
.send_string
= send_string
;
416 api
.testMode
= testMode
;
421 return constructor();