-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_worker.js
62 lines (50 loc) · 1.62 KB
/
shared_worker.js
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
var port;
var ws = null;
var peers = [];
self.addEventListener('connect', function(e) {
port = e.ports[0];
peers.push(port);
port.addEventListener('message', function(e) {
// Start
if (e.data.cmd === 'start') {
var d = new Date();
var n = d.getTime();
if (ws === null) {
// Socket init
ws = new WebSocket(e.data.url);
console.log("Create new socket: " + n);
} else {
console.log("Use old socket: " + n);
}
// On message receive
ws.onmessage = function (msg) {
if (typeof msg != 'undefined' && msg.data != 'undefined') {
send({'operation': 'on_message', 'data': JSON.parse(msg.data)});
}
};
// On error connection
ws.onerror = function () {
ws = null;
send({'operation': 'on_error'});
};
// On close connection
ws.onclose = function (event) {
ws = null;
send({'operation': 'on_close', 'data': event.code});
};
// Send Message
} else if (e.data.cmd === 'send') {
if (ws !== null && ws.readyState === 1) {
ws.send(e.data.data);
}
}
// Отправляем данные клиенту
function send (data) {
console.log(peers);
peers.forEach(function (port) {
port.postMessage(data);
});
}
}, false);
port.start();
}, false);