-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice_worker.js
76 lines (62 loc) · 2.01 KB
/
service_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var port;
var ws = null;
var peers = [];
self.addEventListener('install', (event) => {
console.log('Установлен');
// Activate worker immediately
// event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
console.log('Активирован');
// Become available to all pages
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (event) => {
// console.log('Происходит запрос на сервер');
});
self.addEventListener('message', function (evt) {
if (evt.data.cmd === 'start') {
peers.push(evt.ports[0]);
var d = new Date();
var n = d.getTime();
if (ws === null) {
// Socket init
ws = new WebSocket('ws://curex.ll:8880');
console.log("Create new socket: " + n);
} else {
console.log("Use old socket: " + n);
}
ws.onopen = function () {
// console.log("Open");
return true;
};
// On message receive
ws.onmessage = function (event) {
console.log("Message receive " + event.data);
send_data(event.data);
};
// On error connection
ws.onerror = function (error) {
// console.log("Error " + error.message);
};
// On close connection
ws.onclose = function (event) {
if (event.wasClean) {
// console.log('clean closed');
} else {
// console.log('broken connection');
}
console.log('Code: ' + event.code + ' reason: ' + event.reason);
};
// Отправляем данные клиенту
function send_data(data) {
peers.forEach(function (port) {
port.postMessage(data);
});
}
} else {
// Инитим объект и запускаем опрос
if (ws !== null && ws.readyState === 1)
ws.send(evt.data);
}
});