forked from flowersinthesand/portal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.socket.js
More file actions
1165 lines (1020 loc) · 29.4 KB
/
jquery.socket.js
File metadata and controls
1165 lines (1020 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* jQuery stringifyJSON
* http://github.com/flowersinthesand/jquery-stringifyJSON
*
* Copyright 2011, Donghwan Kim
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
// This plugin is heavily based on Douglas Crockford's reference implementation
(function($) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = {
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
'"' : '\\"',
'\\' : '\\\\'
};
function quote(string) {
return '"' + string.replace(escapable, function(a) {
var c = meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"';
}
function f(n) {
return n < 10 ? "0" + n : n;
}
function str(key, holder) {
var i, v, len, partial, value = holder[key], type = typeof value;
if (value && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON(key);
type = typeof value;
}
switch (type) {
case "string":
return quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
return String(value);
case "object":
if (!value) {
return "null";
}
switch (Object.prototype.toString.call(value)) {
case "[object Date]":
return isFinite(value.valueOf()) ? '"' + value.getUTCFullYear() + "-" + f(value.getUTCMonth() + 1) + "-" + f(value.getUTCDate()) + "T" +
f(value.getUTCHours()) + ":" + f(value.getUTCMinutes()) + ":" + f(value.getUTCSeconds()) + "Z" + '"' : "null";
case "[object Array]":
len = value.length;
partial = [];
for (i = 0; i < len; i++) {
partial.push(str(i, value) || "null");
}
return "[" + partial.join(",") + "]";
default:
partial = [];
for (i in value) {
if (Object.prototype.hasOwnProperty.call(value, i)) {
v = str(i, value);
if (v) {
partial.push(quote(i) + ":" + v);
}
}
}
return "{" + partial.join(",") + "}";
}
}
}
$.stringifyJSON = function(value) {
if (window.JSON && window.JSON.stringify) {
return window.JSON.stringify(value);
}
return str("", {"": value});
};
}(jQuery));
/*
* jQuery Socket
* http://github.com/flowersinthesand/jquery-socket
*
* Copyright 2012, Donghwan Kim
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
(function($, undefined) {
var // Default options
defaults,
// Transports
transports,
// Socket instances
sockets = {},
// A global identifier
guid = $.now(),
// Callback names for JSONP
jsonpCallbacks = [];
// From jQuery.Callbacks
function callbacks(deferred) {
var list = [],
stack = [],
memory,
result,
firing,
firingStart,
firingLength,
firingIndex,
fire = function(context, args) {
args = args || [];
memory = !deferred || [context, args];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for (; firingIndex < firingLength; firingIndex++) {
result = list[firingIndex].apply(context, args);
}
firing = false;
},
self = {
add: function(fn) {
var length = list.length;
if (stack) {
list.push(fn);
if (firing) {
firingLength = list.length;
} else if (memory && memory !== true) {
firingStart = length;
fire(memory[0], memory[1]);
}
}
},
remove: function(fn) {
var i;
if (stack) {
for (i = 0; i < list.length; i++) {
if (fn === list[i] || (fn.guid && fn.guid === list[i].guid)) {
if (firing) {
if (i <= firingLength) {
firingLength--;
if (i <= firingIndex) {
firingIndex--;
}
}
}
list.splice(i--, 1);
}
}
}
},
fire: function(context, args) {
var ret;
if (stack) {
if (firing) {
if (!deferred) {
stack.push([context, args]);
}
} else if (!(deferred && memory)) {
fire(context, args);
}
ret = result;
result = undefined;
}
return ret;
},
lock: function() {
stack = undefined;
},
locked: function() {
return !stack;
},
unlock: function() {
stack = [];
memory = firing = firingStart = firingLength = firingIndex = undefined;
}
};
return self;
}
function isBinary(data) {
var string = Object.prototype.toString.call(data);
return string === "[object Blob]" || string === "[object ArrayBuffer]";
}
function iterate(fn) {
var timeoutId;
// Though the interval is 1ms for real-time application, there is a delay between setTimeout calls
// For detail, see https://developer.mozilla.org/en/window.setTimeout#Minimum_delay_and_timeout_nesting
(function loop() {
timeoutId = setTimeout(function() {
if (fn() === false) {
return;
}
loop();
}, 1);
})();
return function() {
clearTimeout(timeoutId);
};
}
// Socket function
function socket(url, options) {
var // Final options object
opts,
// Socket id,
id,
// Transport
transport,
// Timeout
timeoutTimer,
// Heartbeat
heartbeatTimer,
// The state of the connection
state,
// Event helpers
events = {},
eventId = 0,
// Reply callbacks
replyCallbacks = {},
// Buffer
buffer = [],
// Reconnection
reconnectTimer,
reconnectDelay,
reconnectTry,
// Map of the session-scoped values
session = {},
// Last event id
lastEventId,
// Socket object
self = {
// Finds the value of an option
option: function(key) {
return opts[({id: "_id", url: "_url"})[key] || key] || null;
},
// Gets or sets a session-scoped value
session: function(key, value) {
if (value === undefined) {
return session[key] || null;
}
session[key] = value;
return this;
},
// Returns the state
state: function() {
return state;
},
// Adds event handler
on: function(type, fn) {
var event = events[type];
// For custom event
if (!event) {
if (events.message.locked()) {
return this;
}
event = events[type] = callbacks();
event.order = events.message.order;
}
event.add(fn);
return this;
},
// Removes event handler
off: function(type, fn) {
var event = events[type];
if (event) {
event.remove(fn);
}
return this;
},
// Adds one time event handler
one: function(type, fn) {
function proxy() {
self.off(type, proxy);
fn.apply(this, arguments);
}
fn.guid = fn.guid || guid++;
proxy.guid = fn.guid;
return self.on(type, proxy);
},
// Fires event handlers
fire: function(type, args) {
var event = events[type];
if (event) {
session.result = event.fire(self, args);
}
return this;
},
// Establishes a connection
open: function() {
var candidates = $.makeArray(opts.transports),
type;
// Cancels the scheduled connection
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
// Resets the session scope and event helpers
session = {};
for (type in events) {
events[type].unlock();
}
// Chooses transport
transport = undefined;
session.candidates = candidates;
while (!transport && candidates.length) {
type = candidates.shift();
if (transports[type]) {
session.transport = type;
session.url = self._url();
transport = transports[type](self, opts);
}
}
// Increases the number of reconnection attempts
if (reconnectTry) {
reconnectTry++;
}
// Fires the connecting event and connects
if (transport) {
self.fire("connecting");
transport.open();
} else {
self.close("notransport");
}
return this;
},
// Transmits event using the connection
send: function(event, data, callback) {
// Defers sending an event until the state become opened
if (state !== "opened") {
buffer.push(arguments);
} else {
// Standardize .send(data) and .send(data, callback) into .send(event, data, callback)
if (data === undefined || $.isFunction(data)) {
callback = data;
data = event;
event = "message";
}
eventId++;
replyCallbacks[eventId] = callback;
transport.send(isBinary(data) ? data : opts.outbound.call(self, {
id: eventId,
socket: id,
type: event,
data: data,
reply: !!callback
}));
}
return this;
},
// Disconnects the connection
close: function(/* internal */ reason) {
// Prevents reconnection
if (!reason) {
opts.reconnect = false;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}
if (transport) {
transport.close();
}
// Fires the close event immediately for transport which doesn't give feedback on disconnection
if (reason || !transport || !transport.feedback) {
self.fire("close", [reason || "close"]);
}
return this;
},
// For internal use only
// Fires events from the server
_notify: function(data, isChunk) {
if (isChunk) {
data = opts.chunkParser.call(self, data);
while (data.length) {
self._notify(data.shift());
}
} else {
$.each(isBinary(data) ? [{type: "message", data: data}] : $.makeArray(opts.inbound.call(self, data)),
function(i, event) {
lastEventId = event.id;
session.result = null;
self.fire(event.type, [event.data]);
if (event.reply) {
$.when(session.result).done(function(result) {
self.send("reply", {id: event.id, data: result});
});
}
});
}
return this;
},
// URL generator
_url: function(params) {
return opts.url.call(self, url, $.extend({
id: id,
transport: session.transport,
heartbeat: opts.heartbeat || false,
lastEventId: lastEventId || ""
}, params));
}
},
// From jQuery.ajax
parts = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/.exec(url.toLowerCase());
opts = $.extend(true, {}, defaults, options);
if (options) {
if (options.transports) {
opts.transports = options.transports;
}
}
opts._url = url;
opts._id = id = opts.id.call(self);
opts.crossDomain = !!(parts &&
// protocol and hostname
(parts[1] != location.protocol || parts[2] != location.hostname ||
// port
(parts[3] || (parts[1] === "http:" ? 80 : 443)) != (location.port || (location.protocol === "http:" ? 80 : 443))));
$.each(["connecting", "open", "message", "close", "waiting"], function(i, type) {
// Creates event helper
events[type] = callbacks(type !== "message");
events[type].order = i;
// Shortcuts for on method
var old = self[type],
on = function(fn) {
return self.on(type, fn);
};
self[type] = !old ? on : function(fn) {
return ($.isFunction(fn) ? on : old).apply(this, arguments);
};
});
// Initializes
self.connecting(function() {
state = "connecting";
// Sets timeout timer
if (opts.timeout > 0) {
timeoutTimer = setTimeout(function() {
self.close("timeout");
}, opts.timeout);
}
})
.open(function() {
state = "opened";
// Clears timeout timer
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
// Sets heartbeat timer
if (opts.heartbeat > opts._heartbeat) {
// Helper function for setting heartbeat timer
(function setHeartbeatTimer() {
heartbeatTimer = setTimeout(function() {
self.send("heartbeat", null).one("heartbeat", function() {
clearTimeout(heartbeatTimer);
setHeartbeatTimer();
});
heartbeatTimer = setTimeout(function() {
self.close("error");
}, opts._heartbeat);
}, opts.heartbeat - opts._heartbeat);
})();
}
// Locks the connecting event
events.connecting.lock();
// Initializes variables related with reconnection
reconnectTimer = reconnectDelay = reconnectTry = null;
// Flushes buffer
while (buffer.length) {
self.send.apply(self, buffer.shift());
}
})
.close(function() {
var type, event, order = events.close.order;
state = "closed";
// Clears timers
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
if (heartbeatTimer) {
clearTimeout(heartbeatTimer);
heartbeatTimer = null;
}
// Locks event whose order is lower than close event
for (type in events) {
event = events[type];
if (event.order < order) {
event.lock();
}
}
// Handles reconnection
if (opts.reconnect) {
self.one("close", function() {
reconnectTry = reconnectTry || 1;
reconnectDelay = opts.reconnect.call(self, reconnectDelay, reconnectTry);
if (reconnectDelay !== false) {
reconnectTimer = setTimeout(function() {
self.open();
}, reconnectDelay);
self.fire("waiting", [reconnectDelay, reconnectTry]);
}
});
}
})
.waiting(function() {
state = "waiting";
})
.on("reply", function(reply) {
if (replyCallbacks[reply.id]) {
replyCallbacks[reply.id].call(self, reply.data);
delete replyCallbacks[reply.id];
}
});
return self.open();
}
// Default options
defaults = {
transports: ["ws", "sse", "stream", "longpoll"],
timeout: false,
heartbeat: false,
_heartbeat: 5000,
reconnect: function(lastDelay) {
return 2 * (lastDelay || 250);
},
id: function() {
// Generates a random UUID
// Logic borrowed from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c === "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
url: function(url, params) {
// Adds the current timestamp for this request not to be cached
params._ = $.now();
return url + (/\?/.test(url) ? "&" : "?") + $.param(params);
},
inbound: $.parseJSON,
outbound: $.stringifyJSON,
xdrURL: function(url) {
// Maintaining session by rewriting URL
// http://stackoverflow.com/questions/6453779/maintaining-session-by-rewriting-url
var match = /(?:^|;\s*)(JSESSIONID|PHPSESSID)=([^;]*)/.exec(document.cookie);
switch (match && match[1]) {
case "JSESSIONID":
return url.replace(/;jsessionid=[^\?]*|(\?)|$/, ";jsessionid=" + match[2] + "$1");
case "PHPSESSID":
return url.replace(/\?PHPSESSID=[^&]*&?|\?|$/, "?PHPSESSID=" + match[2] + "&").replace(/&$/, "");
default:
return false;
}
},
chunkParser: function(chunk) {
// Chunks are formatted according to the event stream format
// http://www.w3.org/TR/eventsource/#event-stream-interpretation
var reol = /\r\n|\r|\n/g, lines = [], data = this.session("data"), array = [], i = 0,
match, line;
// String.prototype.split is not reliable cross-browser
while (match = reol.exec(chunk)) {
lines.push(chunk.substring(i, match.index));
i = match.index + match[0].length;
}
lines.push(chunk.length === i ? "" : chunk.substring(i));
if (!data) {
data = [];
this.session("data", data);
}
// Processes the data field only
for (i = 0; i < lines.length; i++) {
line = lines[i];
if (!line) {
// Finish
array.push(data.join("\n"));
data = [];
this.session("data", data);
} else if (/^data:\s/.test(line)) {
// A single data field
data.push(line.substring("data: ".length));
} else {
// A fragment of a data field
data[data.length - 1] += line;
}
}
return array;
},
credentials: false
};
// Transports
transports = {
// WebSocket
ws: function(socket) {
var WebSocket = window.WebSocket || window.MozWebSocket,
ws, aborted;
if (!WebSocket) {
return;
}
return {
feedback: true,
open: function() {
// Makes an absolute url whose scheme is ws or wss
var url = decodeURI($('<a href="' + socket.session("url") + '"/>')[0].href.replace(/^http/, "ws"));
socket.session("url", url);
ws = new WebSocket(url);
ws.onopen = function(event) {
socket.session("event", event).fire("open");
};
ws.onmessage = function(event) {
socket.session("event", event)._notify(event.data);
};
ws.onerror = function(event) {
socket.session("event", event).fire("close", [aborted ? "close" : "error"]);
};
ws.onclose = function(event) {
socket.session("event", event).fire.call(socket, "close", [aborted ? "close" : event.wasClean ? "done" : "error"]);
};
},
send: function(data) {
ws.send(data);
},
close: function() {
aborted = true;
ws.close();
}
};
},
// HTTP Support
http: function(socket, options) {
var send,
sending,
queue = [];
function post() {
if (queue.length) {
send(options._url, queue.shift());
} else {
sending = false;
}
}
// The Content-Type is not application/x-www-form-urlencoded but text/plain on account of XDomainRequest
// See the fourth at http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
send = !options.crossDomain || $.support.cors ?
function(url, data) {
$.ajax(url, {
type: "POST",
contentType: "text/plain; charset=UTF-8",
data: "data=" + data,
async: true,
timeout: false,
xhrFields: $.support.cors ? {withCredentials: options.credentials} : null
})
.always(post);
} : window.XDomainRequest && options.xdrURL && options.xdrURL.call(socket, "t") ?
function(url, data) {
var xdr = new window.XDomainRequest();
xdr.onload = xdr.onerror = post;
xdr.open("POST", options.xdrURL.call(socket, url));
xdr.send("data=" + data);
} :
function(url, data) {
var $form = $("<form method='POST' enctype='text/plain' accept-charset='UTF-8' />"),
$iframe = $("<iframe name='socket-" + (++guid) + "'/>");
$form.attr({action: url, target: $iframe.attr("name")}).hide().appendTo("body")
.append($("<textarea name='data' />").val(data))
.append($iframe)
.submit();
$iframe.load(function() {
$form.remove();
post();
});
};
return {
send: function(data) {
queue.push(data);
if (!sending) {
sending = true;
post();
}
}
};
},
// Server-Sent Events
sse: function(socket, options) {
var EventSource = window.EventSource,
es;
if (!EventSource) {
return;
} else if (options.crossDomain) {
try {
if (!("withCredentials" in new EventSource("about:blank"))) {
return;
}
} catch(e) {
return;
}
}
return $.extend(transports.http(socket, options), {
open: function() {
es = new EventSource(socket.session("url"), {withCredentials: options.credentials});
es.onopen = function(event) {
socket.session("event", event).fire("open");
};
es.onmessage = function(event) {
socket.session("event", event)._notify(event.data);
};
es.onerror = function(event) {
es.close();
// There is no way to find whether this connection closed normally or not
socket.session("event", event).fire("close", ["done"]);
};
},
close: function() {
es.close();
}
});
},
// Streaming facade
stream: function(socket) {
socket.session("candidates").unshift("streamxdr", "streamiframe", "streamxhr");
},
// Streaming - XMLHttpRequest
streamxhr: function(socket, options) {
var XMLHttpRequest = window.XMLHttpRequest,
xhr, aborted;
if (!XMLHttpRequest || window.XDomainRequest || window.ActiveXObject || (options.crossDomain && !$.support.cors)) {
return;
}
return $.extend(transports.http(socket, options), {
open: function() {
var stop;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
function onprogress() {
var index = socket.session("index"),
length = xhr.responseText.length;
if (!index) {
socket.fire("open");
} else if (length > index) {
socket._notify(xhr.responseText.substring(index, length), true);
}
socket.session("index", length);
}
if (xhr.readyState === 3 && xhr.status === 200) {
// Despite the change in response, Opera doesn't fire the readystatechange event
if ($.browser.opera && !stop) {
stop = iterate(onprogress);
} else {
onprogress();
}
} else if (xhr.readyState === 4) {
if (stop) {
stop();
}
socket.fire.call(socket, "close", [aborted ? "close" : xhr.status === 200 ? "done" : "error"]);
}
};
xhr.open("GET", socket.session("url"));
xhr.withCredentials = options.credentials;
xhr.send(null);
},
close: function() {
aborted = true;
xhr.abort();
}
});
},
// Streaming - Iframe
streamiframe: function(socket, options) {
var ActiveXObject = window.ActiveXObject,
doc, stop;
if (!ActiveXObject || options.crossDomain) {
return;
}
return $.extend(transports.http(socket, options), {
open: function() {
var iframe, cdoc;
doc = new ActiveXObject("htmlfile");
doc.open();
doc.close();
iframe = doc.createElement("iframe");
iframe.src = socket.session("url");
doc.body.appendChild(iframe);
cdoc = iframe.contentDocument || iframe.contentWindow.document;
stop = iterate(function() {
if (!cdoc.firstChild) {
return;
}
var response = cdoc.body.lastChild;
// Detects connection failure
if (!response) {
socket.fire("close", ["error"]);
return false;
}
response.innerText = "";
socket.fire("open");
stop = iterate(function() {
var clone = response.cloneNode(true),
text;
// Adds a character not CR and LF to circumvent an Internet Explorer bug
// If the contents of an element ends with one or more CR or LF, Internet Explorer ignores them in the innerText property
clone.appendChild(cdoc.createTextNode("."));
text = clone.innerText;
text = text.substring(0, text.length - 1);
if (text) {
response.innerText = "";
socket._notify(text, true);
}
if (cdoc.readyState === "complete") {
socket.fire("close", ["done"]);
return false;
}
});
return false;
});
},
close: function() {
stop();
doc.execCommand("Stop");
}
});
},
// Streaming - XDomainRequest
streamxdr: function(socket, options) {
var XDomainRequest = window.XDomainRequest,
xdr;
if (!XDomainRequest || !options.xdrURL || !options.xdrURL.call(socket, "t")) {
return;
}
return $.extend(transports.http(socket, options), {
open: function() {
var url = options.xdrURL.call(socket, socket.session("url"));
socket.session("url", url);
xdr = new XDomainRequest();
xdr.onprogress = function() {
var index = socket.session("index"),
length = xdr.responseText.length;
if (!index) {
socket.fire("open");
} else {
socket._notify(xdr.responseText.substring(index, length), true);
}
socket.session("index", length);
};
xdr.onerror = function() {
socket.fire("close", ["error"]);
};
xdr.onload = function() {
socket.fire("close", ["done"]);
};
xdr.open("GET", url);
xdr.send();
},
close: function() {
xdr.abort();
}
});
},
// Long polling facade
longpoll: function(socket) {
socket.session("candidates").unshift("longpollajax", "longpollxdr", "longpolljsonp");
},
// Long polling - AJAX
longpollajax: function(socket, options) {
var count = 0, xhr;
if (!$.support.ajax || (options.crossDomain && !$.support.cors)) {
return;
}
function poll() {
var url = socket._url({count: ++count}),
done = function(data) {
if (data || count === 1) {
if (count === 1) {
socket.fire("open");
}
if (data) {
socket._notify(data);
}
poll();
} else {
socket.fire("close", ["done"]);