-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-socket.html
More file actions
69 lines (58 loc) · 2 KB
/
web-socket.html
File metadata and controls
69 lines (58 loc) · 2 KB
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
<link rel="import" href="../polymer/polymer.html">
<polymer-element name="web-socket" attributes="url message auto handleAs sendAs">
<script>
Polymer('web-socket', {
ws: null,
url: '',
auto: false,
handleAs: 'text',
sendAs: 'text',
wsOnOpen: function() {
this.fire('open');
this.autoGo();
},
wsOnMessage: function(e) {
if (this.handleAs == 'json') {
this.fire('message', JSON.parse(e.data));
} else {
this.fire('message', e.data);
}
},
wsOnClose: function() {
this.fire('close');
},
wsOnError: function(e) {
this.fire('error', e);
},
initialiseWebSocket: function() {
this.ws = new WebSocket(this.url);
this.ws.onopen = this.wsOnOpen.bind(this);
this.ws.onmessage = this.wsOnMessage.bind(this);
this.ws.onclose = this.wsOnClose.bind(this);
this.ws.onerror = this.wsOnError.bind(this);
},
urlChanged: function() {
this.initialiseWebSocket();
},
messageChanged: function() {
this.autoGo();
},
autoGo: function() {
if (this.auto) {
this.go();
}
},
go: function() {
if (this.ws == null || (this.ws.readyState != 0 && this.ws.readyState != 1)) {
this.initialiseWebSocket();
} else if (this.ws.readyState == 1 && this.message != undefined) {
if (this.sendAs == "json") {
this.ws.send(JSON.stringify(this.message));
} else {
this.ws.send(this.message);
}
}
}
})
</script>
</polymer-element>