-
Notifications
You must be signed in to change notification settings - Fork 1
/
pusher.js
67 lines (55 loc) · 1.74 KB
/
pusher.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
var pushServer = window.location.hostname + ':8095/';
var pusher = null;
var callbacks = {};
function makeEvent() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + pushServer + 'pub?intent=channelname.taskname.12345&obj={"id":123}', false);
xhr.send();
}
function connectPusher(onConnect) {
pusher = new WebSocket("ws://" + pushServer + "sub");
pusher.onopen = function () {
console.log("Pusher Connected");
onConnect();
};
pusher.onclose = function (event) {
if (event.wasClean) {
console.log('Pusher Connection closed gracefull');
} else {
console.log('Pusher Connection closed')
}
console.log('Pusher disconnect code: ' + event.code + ' reason: ' + event.reason);
};
pusher.onmessage = function (event) {
console.log("Pusher Received data: " + event.data);
var jdata = JSON.parse(event.data);
var cb = callbacks[jdata.intent];
if (cb != undefined) {
var obj = jdata.obj;
if (obj) {
try {
obj = JSON.parse(obj);
} catch (e) {
}
}
cb(obj);
}
};
pusher.onerror = function (error) {
console.log("Pusher Error: " + error.message);
};
}
function pushSub(intent, callback) {
if (pusher == null) {
connectPusher(function () {
pusher.send('{"op": "sub", "intent": "' + intent + '"}');
callbacks[intent] = callback;
});
} else {
pusher.send('{"op": "sub", "intent": "' + intent + '"}');
callbacks[intent] = callback;
}
}
function pushUnsub(intent) {
pusher.send('{"op": "unsub", "intent": "' + intent + '"}');
}