-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathweb-socket.html
224 lines (192 loc) · 5.51 KB
/
web-socket.html
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<link rel="import" href="../polymer/polymer.html">
<!--
A Polymer element to ease the use and configuration of WebSockets.
Example:
<web-socket url="ws://echo.websocket.org"
auto json
on-open="_onOpen"
on-close="_onClose"
on-message="_onMessage"
on-error="_onError">
</web-socket>
The above example shows how to establish a WebSocket connection with
`<web-socket>` in a [Polymer](https://www.polymer-project.org) app. This simple
declarative element definition is:
- Establishing a connection to `ws://echo.websocket.org`.
- Automatically connecting on page load.
- Parsing and stringifying JSON automatically.
- Automatically reconnecting in the event of an unclean close event (a default
behaviour of this library - no configuration required through properties).
- Setting up event handlers to functions declared externally (`_onOpen`,
`_onClose`, etc - defined by a parent element, such as a page).
@element web-socket
@demo demo/index.html
-->
<script>
Polymer({
is: 'web-socket',
properties: {
/**
* The URL to which to connect; this should be the URL to which the
* WebSocket server will respond.
*/
url: {
type: String,
observer: '_urlChanged'
},
/**
* An array of protocol strings.
*/
protocols: {
type: Array,
value: []
},
/**
* Automatically encode sent messages to JSON and attempt to parse
* incoming messages into an Object from JSON.
*/
json: {
type: Boolean,
value: false
},
/**
* Automatically open WebSocket on `attach`.
*/
auto: {
type: Boolean,
value: false
},
/**
* Disable exponential backoff during reconnection attempts.
*/
noDecay: {
type: Boolean,
value: false
},
/**
* Initial delay before attempting to reopen the connection in the event
* that it was not closed cleanly. The interval will decay exponentially.
*/
_reopenInterval: {
type: Number,
value: 100
}
},
ready: function() {
this._config = {
_reopenInterval: this._reopenInterval
};
},
attached: function () {
if (this.auto) {
this.open();
}
},
detached: function () {
this.close();
},
/**
* Instantiates an instance of WebSocket, establishing connection with the
* remote host if url is set and sets up event handlers. Replaces existing
* instance, if present.
*/
open: function () {
if (!this.url) {
throw Error('url property is required');
}
this._websocket = new WebSocket(this.url, this.protocols);
this._websocket.onopen = this._onOpen.bind(this);
this._websocket.onclose = this._onClose.bind(this);
this._websocket.onmessage = this._onMessage.bind(this);
this._websocket.onerror = this._onError.bind(this);
},
/**
* Closes the WebSocket connection or connection attempt, if any. If the
* connection is already closed, this method does nothing.
*/
close: function () {
if (this._websocket) {
this._websocket.close();
this._websocket = null;
}
},
/**
* Transmits data to the server over the WebSocket connection.
* @param {String} data A text string to send to the server.
*/
send: function (data) {
if (!this._websocket) {
return;
}
if (this.json && data !== null && typeof data === 'object') {
data = JSON.stringify(data);
}
this._websocket.send(data);
},
/**
* Fired when the WebSocket is opened.
* @event open
*/
_onOpen: function () {
// Reset reopen interval and remove any pending callbacks.
this._reopenInterval = this._config._reopenInterval;
this.cancelAsync(this._reopenAttempt);
this.fire('open');
},
/**
* Fired when the WebSocket is closed.
* @event close
* @param {Object} event A CloseEvent event object.
*/
_onClose: function (event) {
if (!event.wasClean) {
if (this.noDecay) {
this.async(this.open);
} else {
this._reopenAttempt = this.async(this.open, this._reopenInterval);
this._reopenInterval *= 2;
}
}
this.fire('close');
},
/**
* Fired when a message is received.
* @event message
* @param {Object} event Text string message in `event.detail`.
*/
_onMessage: function (event) {
if (!this._websocket) {
return;
}
var data = event.data;
if (this.json && typeof data === 'string' || data instanceof String) {
try {
data = JSON.parse(data);
} catch (error) {
this.fire('error', error);
}
}
this.fire('message', data);
},
/**
* Fired when the WebSocket raises an error.
* @event error
* @param {Object} event Error object in `event.detail`.
*/
_onError: function (event) {
this.fire('error', event);
},
/**
* Fired when the value of the `url` property changes.
* @event url-changed
* @param {String} currentUrl The current URL.
* @param {String} previousUrl The previous URL.
*/
_urlChanged: function (currentUrl, previousUrl) {
this.fire('url-changed', {
currentUrl: currentUrl,
previousUrl: previousUrl
});
}
});
</script>