Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagecell
Path: blob/master/js/multisockjs.js
447 views
1
import { URLs } from "./urls";
2
import SockJS from "sockjs-client";
3
import utils from "./utils";
4
import { console } from "./console";
5
6
export function MultiSockJS(url, prefix) {
7
console.debug(
8
"Starting sockjs connection to " + url + " with prefix " + prefix
9
);
10
if (
11
!MultiSockJS.sockjs ||
12
MultiSockJS.sockjs.readyState === SockJS.CLOSING ||
13
MultiSockJS.sockjs.readyState === SockJS.CLOSED
14
) {
15
MultiSockJS.channels = {};
16
MultiSockJS.to_init = [];
17
console.debug("Initializing MultiSockJS to " + URLs.sockjs);
18
MultiSockJS.sockjs = new SockJS(
19
URLs.sockjs + "?CellSessionID=" + utils.cellSessionID()
20
);
21
22
MultiSockJS.sockjs.onopen = function (e) {
23
while (MultiSockJS.to_init.length > 0) {
24
MultiSockJS.to_init.shift().init_socket(e);
25
}
26
};
27
28
MultiSockJS.sockjs.onmessage = function (e) {
29
var i = e.data.indexOf(",");
30
var prefix = e.data.substring(0, i);
31
console.debug("MultiSockJS.sockjs.onmessage prefix: " + prefix);
32
e.data = e.data.substring(i + 1);
33
console.debug("other data: " + e.data);
34
if (
35
MultiSockJS.channels[prefix] &&
36
MultiSockJS.channels[prefix].onmessage
37
) {
38
MultiSockJS.channels[prefix].onmessage(e);
39
}
40
};
41
42
MultiSockJS.sockjs.onclose = function (e) {
43
var readyState = MultiSockJS.sockjs.readyState;
44
for (var prefix in MultiSockJS.channels) {
45
MultiSockJS.channels[prefix].readyState = readyState;
46
if (MultiSockJS.channels[prefix].onclose) {
47
MultiSockJS.channels[prefix].onclose(e);
48
}
49
}
50
// Maybe we should just remove the sockjs object from MultiSockJS now
51
};
52
}
53
this.prefix = url
54
? url.match(/^\w+:\/\/.*?\/kernel\/(.*\/channels).*$/)[1]
55
: prefix;
56
console.debug("this.prefix: " + this.prefix);
57
this.readyState = MultiSockJS.sockjs.readyState;
58
MultiSockJS.channels[this.prefix] = this;
59
this.init_socket();
60
}
61
62
MultiSockJS.prototype.init_socket = function (e) {
63
if (MultiSockJS.sockjs.readyState) {
64
var that = this;
65
// Run the onopen function after the current thread has finished,
66
// so that onopen has a chance to be set.
67
setTimeout(function () {
68
that.readyState = MultiSockJS.sockjs.readyState;
69
if (that.onopen) {
70
that.onopen(e);
71
}
72
}, 0);
73
} else {
74
MultiSockJS.to_init.push(this);
75
}
76
};
77
78
MultiSockJS.prototype.send = function (msg) {
79
MultiSockJS.sockjs.send(this.prefix + "," + msg);
80
};
81
82
MultiSockJS.prototype.close = function () {
83
delete MultiSockJS.channels[this.prefix];
84
};
85
86
export default MultiSockJS;
87
88