forked from storyteller/Storyteller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommunicator.js
60 lines (44 loc) · 1.16 KB
/
communicator.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
var Postal = require('postal');
function Communicator(dispatch, address, disconnect){
this.socket = new WebSocket(address);
this.socket.onclose = function(){
console.log('The socket closed');
disconnect();
};
this.socket.onerror = function(evt){
console.log(JSON.stringify(evt));
}
this.socket.onmessage = function(evt){
var message = JSON.parse(evt.data);
console.log('Got: ' + JSON.stringify(message) + ' with topic ' + message.type);
if (message.type == 'refresh-page'){
location.reload();
return;
}
dispatch(message);
};
this.socket.onopen = function(){
console.log('Opened a socket at ' + address);
}
this.send = function(message){
if (this.socket.readyState != 1){
disconnect();
}
else {
var json = JSON.stringify(message);
console.log('Sending to engine: ' + json);
this.socket.send(json);
}
}
var self = this;
Postal.subscribe({
channel: 'engine-request',
topic: '*',
callback: function(data, envelope){
data.type = envelope.topic;
console.log("Sending message to server: " + JSON.stringify(data));
self.send(data);
}
});
}
module.exports = Communicator;