@fairwords/websocket 1.0.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/websocket-tests.yml +16 -0
- package/.jshintrc +88 -0
- package/CHANGELOG.md +291 -0
- package/Jenkinsfile +7 -0
- package/LICENSE +177 -0
- package/Makefile +5 -0
- package/README.md +255 -0
- package/gulpfile.js +14 -0
- package/index.js +1 -0
- package/lib/Deprecation.js +32 -0
- package/lib/W3CWebSocket.js +257 -0
- package/lib/WebSocketClient.js +361 -0
- package/lib/WebSocketConnection.js +896 -0
- package/lib/WebSocketFrame.js +280 -0
- package/lib/WebSocketRequest.js +541 -0
- package/lib/WebSocketRouter.js +157 -0
- package/lib/WebSocketRouterRequest.js +54 -0
- package/lib/WebSocketServer.js +256 -0
- package/lib/browser.js +54 -0
- package/lib/utils.js +66 -0
- package/lib/version.js +1 -0
- package/lib/websocket.js +11 -0
- package/package.json +58 -0
- package/vendor/FastBufferList.js +191 -0
package/README.md
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
WebSocket Client & Server Implementation for Node
|
|
2
|
+
=================================================
|
|
3
|
+
|
|
4
|
+
[](http://badge.fury.io/js/websocket)
|
|
5
|
+
|
|
6
|
+
[](https://www.npmjs.com/package/websocket)
|
|
7
|
+
|
|
8
|
+
[ ](https://codeship.com/projects/61106)
|
|
9
|
+
|
|
10
|
+
Overview
|
|
11
|
+
--------
|
|
12
|
+
This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
Documentation
|
|
16
|
+
=============
|
|
17
|
+
|
|
18
|
+
[You can read the full API documentation in the docs folder.](docs/index.md)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
Changelog
|
|
22
|
+
---------
|
|
23
|
+
|
|
24
|
+
***Current Version: 1.0.34*** - Release 2021-04-14
|
|
25
|
+
|
|
26
|
+
* Updated browser shim to use the native `globalThis` property when available. See [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) for context. Resolves [#415](https://github.com/theturtle32/WebSocket-Node/issues/415)
|
|
27
|
+
|
|
28
|
+
[View the full changelog](CHANGELOG.md)
|
|
29
|
+
|
|
30
|
+
Browser Support
|
|
31
|
+
---------------
|
|
32
|
+
|
|
33
|
+
All current browsers are fully* supported.
|
|
34
|
+
|
|
35
|
+
* Firefox 7-9 (Old) (Protocol Version 8)
|
|
36
|
+
* Firefox 10+ (Protocol Version 13)
|
|
37
|
+
* Chrome 14,15 (Old) (Protocol Version 8)
|
|
38
|
+
* Chrome 16+ (Protocol Version 13)
|
|
39
|
+
* Internet Explorer 10+ (Protocol Version 13)
|
|
40
|
+
* Safari 6+ (Protocol Version 13)
|
|
41
|
+
|
|
42
|
+
(Not all W3C WebSocket features are supported by browsers. More info in the [Full API documentation](docs/index.md))
|
|
43
|
+
|
|
44
|
+
Benchmarks
|
|
45
|
+
----------
|
|
46
|
+
There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.
|
|
47
|
+
|
|
48
|
+
(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)
|
|
49
|
+
|
|
50
|
+
Autobahn Tests
|
|
51
|
+
--------------
|
|
52
|
+
The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability.
|
|
53
|
+
|
|
54
|
+
- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/)
|
|
55
|
+
|
|
56
|
+
Installation
|
|
57
|
+
------------
|
|
58
|
+
|
|
59
|
+
In your project root:
|
|
60
|
+
|
|
61
|
+
$ npm install websocket
|
|
62
|
+
|
|
63
|
+
Then in your code:
|
|
64
|
+
|
|
65
|
+
```javascript
|
|
66
|
+
var WebSocketServer = require('websocket').server;
|
|
67
|
+
var WebSocketClient = require('websocket').client;
|
|
68
|
+
var WebSocketFrame = require('websocket').frame;
|
|
69
|
+
var WebSocketRouter = require('websocket').router;
|
|
70
|
+
var W3CWebSocket = require('websocket').w3cwebsocket;
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Current Features:
|
|
74
|
+
-----------------
|
|
75
|
+
- Licensed under the Apache License, Version 2.0
|
|
76
|
+
- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
|
|
77
|
+
- Can handle/aggregate received fragmented messages
|
|
78
|
+
- Can fragment outgoing messages
|
|
79
|
+
- Router to mount multiple applications to various path and protocol combinations
|
|
80
|
+
- TLS supported for outbound connections via WebSocketClient
|
|
81
|
+
- TLS supported for server connections (use https.createServer instead of http.createServer)
|
|
82
|
+
- Thanks to [pors](https://github.com/pors) for confirming this!
|
|
83
|
+
- Cookie setting and parsing
|
|
84
|
+
- Tunable settings
|
|
85
|
+
- Max Receivable Frame Size
|
|
86
|
+
- Max Aggregate ReceivedMessage Size
|
|
87
|
+
- Whether to fragment outgoing messages
|
|
88
|
+
- Fragmentation chunk size for outgoing messages
|
|
89
|
+
- Whether to automatically send ping frames for the purposes of keepalive
|
|
90
|
+
- Keep-alive ping interval
|
|
91
|
+
- Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
|
|
92
|
+
- How long to wait after sending a close frame for acknowledgment before closing the socket.
|
|
93
|
+
- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class).
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
Known Issues/Missing Features:
|
|
97
|
+
------------------------------
|
|
98
|
+
- No API for user-provided protocol extensions.
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
Usage Examples
|
|
102
|
+
==============
|
|
103
|
+
|
|
104
|
+
Server Example
|
|
105
|
+
--------------
|
|
106
|
+
|
|
107
|
+
Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
|
|
108
|
+
|
|
109
|
+
```javascript
|
|
110
|
+
#!/usr/bin/env node
|
|
111
|
+
var WebSocketServer = require('websocket').server;
|
|
112
|
+
var http = require('http');
|
|
113
|
+
|
|
114
|
+
var server = http.createServer(function(request, response) {
|
|
115
|
+
console.log((new Date()) + ' Received request for ' + request.url);
|
|
116
|
+
response.writeHead(404);
|
|
117
|
+
response.end();
|
|
118
|
+
});
|
|
119
|
+
server.listen(8080, function() {
|
|
120
|
+
console.log((new Date()) + ' Server is listening on port 8080');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
wsServer = new WebSocketServer({
|
|
124
|
+
httpServer: server,
|
|
125
|
+
// You should not use autoAcceptConnections for production
|
|
126
|
+
// applications, as it defeats all standard cross-origin protection
|
|
127
|
+
// facilities built into the protocol and the browser. You should
|
|
128
|
+
// *always* verify the connection's origin and decide whether or not
|
|
129
|
+
// to accept it.
|
|
130
|
+
autoAcceptConnections: false
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
function originIsAllowed(origin) {
|
|
134
|
+
// put logic here to detect whether the specified origin is allowed.
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
wsServer.on('request', function(request) {
|
|
139
|
+
if (!originIsAllowed(request.origin)) {
|
|
140
|
+
// Make sure we only accept requests from an allowed origin
|
|
141
|
+
request.reject();
|
|
142
|
+
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
var connection = request.accept('echo-protocol', request.origin);
|
|
147
|
+
console.log((new Date()) + ' Connection accepted.');
|
|
148
|
+
connection.on('message', function(message) {
|
|
149
|
+
if (message.type === 'utf8') {
|
|
150
|
+
console.log('Received Message: ' + message.utf8Data);
|
|
151
|
+
connection.sendUTF(message.utf8Data);
|
|
152
|
+
}
|
|
153
|
+
else if (message.type === 'binary') {
|
|
154
|
+
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
|
|
155
|
+
connection.sendBytes(message.binaryData);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
connection.on('close', function(reasonCode, description) {
|
|
159
|
+
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Client Example
|
|
165
|
+
--------------
|
|
166
|
+
|
|
167
|
+
This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
|
|
168
|
+
|
|
169
|
+
*This code demonstrates a client in Node.js, not in the browser*
|
|
170
|
+
|
|
171
|
+
```javascript
|
|
172
|
+
#!/usr/bin/env node
|
|
173
|
+
var WebSocketClient = require('websocket').client;
|
|
174
|
+
|
|
175
|
+
var client = new WebSocketClient();
|
|
176
|
+
|
|
177
|
+
client.on('connectFailed', function(error) {
|
|
178
|
+
console.log('Connect Error: ' + error.toString());
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
client.on('connect', function(connection) {
|
|
182
|
+
console.log('WebSocket Client Connected');
|
|
183
|
+
connection.on('error', function(error) {
|
|
184
|
+
console.log("Connection Error: " + error.toString());
|
|
185
|
+
});
|
|
186
|
+
connection.on('close', function() {
|
|
187
|
+
console.log('echo-protocol Connection Closed');
|
|
188
|
+
});
|
|
189
|
+
connection.on('message', function(message) {
|
|
190
|
+
if (message.type === 'utf8') {
|
|
191
|
+
console.log("Received: '" + message.utf8Data + "'");
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
function sendNumber() {
|
|
196
|
+
if (connection.connected) {
|
|
197
|
+
var number = Math.round(Math.random() * 0xFFFFFF);
|
|
198
|
+
connection.sendUTF(number.toString());
|
|
199
|
+
setTimeout(sendNumber, 1000);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
sendNumber();
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
client.connect('ws://localhost:8080/', 'echo-protocol');
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Client Example using the *W3C WebSocket API*
|
|
209
|
+
--------------------------------------------
|
|
210
|
+
|
|
211
|
+
Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/).
|
|
212
|
+
|
|
213
|
+
```javascript
|
|
214
|
+
var W3CWebSocket = require('websocket').w3cwebsocket;
|
|
215
|
+
|
|
216
|
+
var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
|
|
217
|
+
|
|
218
|
+
client.onerror = function() {
|
|
219
|
+
console.log('Connection Error');
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
client.onopen = function() {
|
|
223
|
+
console.log('WebSocket Client Connected');
|
|
224
|
+
|
|
225
|
+
function sendNumber() {
|
|
226
|
+
if (client.readyState === client.OPEN) {
|
|
227
|
+
var number = Math.round(Math.random() * 0xFFFFFF);
|
|
228
|
+
client.send(number.toString());
|
|
229
|
+
setTimeout(sendNumber, 1000);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
sendNumber();
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
client.onclose = function() {
|
|
236
|
+
console.log('echo-protocol Client Closed');
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
client.onmessage = function(e) {
|
|
240
|
+
if (typeof e.data === 'string') {
|
|
241
|
+
console.log("Received: '" + e.data + "'");
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Request Router Example
|
|
247
|
+
----------------------
|
|
248
|
+
|
|
249
|
+
For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
Resources
|
|
253
|
+
---------
|
|
254
|
+
|
|
255
|
+
A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered)
|
package/gulpfile.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dependencies.
|
|
3
|
+
*/
|
|
4
|
+
var gulp = require('gulp');
|
|
5
|
+
var jshint = require('gulp-jshint');
|
|
6
|
+
|
|
7
|
+
gulp.task('lint', function() {
|
|
8
|
+
return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js'])
|
|
9
|
+
.pipe(jshint('.jshintrc'))
|
|
10
|
+
.pipe(jshint.reporter('jshint-stylish', {verbose: true}))
|
|
11
|
+
.pipe(jshint.reporter('fail'));
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
gulp.task('default', gulp.series('lint'));
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./lib/websocket');
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/************************************************************************
|
|
2
|
+
* Copyright 2010-2015 Brian McKelvey.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
***********************************************************************/
|
|
16
|
+
|
|
17
|
+
var Deprecation = {
|
|
18
|
+
disableWarnings: false,
|
|
19
|
+
|
|
20
|
+
deprecationWarningMap: {
|
|
21
|
+
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
warn: function(deprecationName) {
|
|
25
|
+
if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) {
|
|
26
|
+
console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]);
|
|
27
|
+
this.deprecationWarningMap[deprecationName] = false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
module.exports = Deprecation;
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/************************************************************************
|
|
2
|
+
* Copyright 2010-2015 Brian McKelvey.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
***********************************************************************/
|
|
16
|
+
|
|
17
|
+
var WebSocketClient = require('./WebSocketClient');
|
|
18
|
+
var toBuffer = require('typedarray-to-buffer');
|
|
19
|
+
var yaeti = require('yaeti');
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
const CONNECTING = 0;
|
|
23
|
+
const OPEN = 1;
|
|
24
|
+
const CLOSING = 2;
|
|
25
|
+
const CLOSED = 3;
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
module.exports = W3CWebSocket;
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig) {
|
|
32
|
+
// Make this an EventTarget.
|
|
33
|
+
yaeti.EventTarget.call(this);
|
|
34
|
+
|
|
35
|
+
// Sanitize clientConfig.
|
|
36
|
+
clientConfig = clientConfig || {};
|
|
37
|
+
clientConfig.assembleFragments = true; // Required in the W3C API.
|
|
38
|
+
|
|
39
|
+
var self = this;
|
|
40
|
+
|
|
41
|
+
this._url = url;
|
|
42
|
+
this._readyState = CONNECTING;
|
|
43
|
+
this._protocol = undefined;
|
|
44
|
+
this._extensions = '';
|
|
45
|
+
this._bufferedAmount = 0; // Hack, always 0.
|
|
46
|
+
this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob.
|
|
47
|
+
|
|
48
|
+
// The WebSocketConnection instance.
|
|
49
|
+
this._connection = undefined;
|
|
50
|
+
|
|
51
|
+
// WebSocketClient instance.
|
|
52
|
+
this._client = new WebSocketClient(clientConfig);
|
|
53
|
+
|
|
54
|
+
this._client.on('connect', function(connection) {
|
|
55
|
+
onConnect.call(self, connection);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
this._client.on('connectFailed', function() {
|
|
59
|
+
onConnectFailed.call(self);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
this._client.connect(url, protocols, origin, headers, requestOptions);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
// Expose W3C read only attributes.
|
|
67
|
+
Object.defineProperties(W3CWebSocket.prototype, {
|
|
68
|
+
url: { get: function() { return this._url; } },
|
|
69
|
+
readyState: { get: function() { return this._readyState; } },
|
|
70
|
+
protocol: { get: function() { return this._protocol; } },
|
|
71
|
+
extensions: { get: function() { return this._extensions; } },
|
|
72
|
+
bufferedAmount: { get: function() { return this._bufferedAmount; } }
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
// Expose W3C write/read attributes.
|
|
77
|
+
Object.defineProperties(W3CWebSocket.prototype, {
|
|
78
|
+
binaryType: {
|
|
79
|
+
get: function() {
|
|
80
|
+
return this._binaryType;
|
|
81
|
+
},
|
|
82
|
+
set: function(type) {
|
|
83
|
+
// TODO: Just 'arraybuffer' supported.
|
|
84
|
+
if (type !== 'arraybuffer') {
|
|
85
|
+
throw new SyntaxError('just "arraybuffer" type allowed for "binaryType" attribute');
|
|
86
|
+
}
|
|
87
|
+
this._binaryType = type;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
// Expose W3C readyState constants into the WebSocket instance as W3C states.
|
|
94
|
+
[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
|
|
95
|
+
Object.defineProperty(W3CWebSocket.prototype, property[0], {
|
|
96
|
+
get: function() { return property[1]; }
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Also expose W3C readyState constants into the WebSocket class (not defined by the W3C,
|
|
101
|
+
// but there are so many libs relying on them).
|
|
102
|
+
[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
|
|
103
|
+
Object.defineProperty(W3CWebSocket, property[0], {
|
|
104
|
+
get: function() { return property[1]; }
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
W3CWebSocket.prototype.send = function(data) {
|
|
110
|
+
if (this._readyState !== OPEN) {
|
|
111
|
+
throw new Error('cannot call send() while not connected');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Text.
|
|
115
|
+
if (typeof data === 'string' || data instanceof String) {
|
|
116
|
+
this._connection.sendUTF(data);
|
|
117
|
+
}
|
|
118
|
+
// Binary.
|
|
119
|
+
else {
|
|
120
|
+
// Node Buffer.
|
|
121
|
+
if (data instanceof Buffer) {
|
|
122
|
+
this._connection.sendBytes(data);
|
|
123
|
+
}
|
|
124
|
+
// If ArrayBuffer or ArrayBufferView convert it to Node Buffer.
|
|
125
|
+
else if (data.byteLength || data.byteLength === 0) {
|
|
126
|
+
data = toBuffer(data);
|
|
127
|
+
this._connection.sendBytes(data);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
throw new Error('unknown binary data:', data);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
W3CWebSocket.prototype.close = function(code, reason) {
|
|
137
|
+
switch(this._readyState) {
|
|
138
|
+
case CONNECTING:
|
|
139
|
+
// NOTE: We don't have the WebSocketConnection instance yet so no
|
|
140
|
+
// way to close the TCP connection.
|
|
141
|
+
// Artificially invoke the onConnectFailed event.
|
|
142
|
+
onConnectFailed.call(this);
|
|
143
|
+
// And close if it connects after a while.
|
|
144
|
+
this._client.on('connect', function(connection) {
|
|
145
|
+
if (code) {
|
|
146
|
+
connection.close(code, reason);
|
|
147
|
+
} else {
|
|
148
|
+
connection.close();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
break;
|
|
152
|
+
case OPEN:
|
|
153
|
+
this._readyState = CLOSING;
|
|
154
|
+
if (code) {
|
|
155
|
+
this._connection.close(code, reason);
|
|
156
|
+
} else {
|
|
157
|
+
this._connection.close();
|
|
158
|
+
}
|
|
159
|
+
break;
|
|
160
|
+
case CLOSING:
|
|
161
|
+
case CLOSED:
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Private API.
|
|
169
|
+
*/
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
function createCloseEvent(code, reason) {
|
|
173
|
+
var event = new yaeti.Event('close');
|
|
174
|
+
|
|
175
|
+
event.code = code;
|
|
176
|
+
event.reason = reason;
|
|
177
|
+
event.wasClean = (typeof code === 'undefined' || code === 1000);
|
|
178
|
+
|
|
179
|
+
return event;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
function createMessageEvent(data) {
|
|
184
|
+
var event = new yaeti.Event('message');
|
|
185
|
+
|
|
186
|
+
event.data = data;
|
|
187
|
+
|
|
188
|
+
return event;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
function onConnect(connection) {
|
|
193
|
+
var self = this;
|
|
194
|
+
|
|
195
|
+
this._readyState = OPEN;
|
|
196
|
+
this._connection = connection;
|
|
197
|
+
this._protocol = connection.protocol;
|
|
198
|
+
this._extensions = connection.extensions;
|
|
199
|
+
|
|
200
|
+
this._connection.on('close', function(code, reason) {
|
|
201
|
+
onClose.call(self, code, reason);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
this._connection.on('message', function(msg) {
|
|
205
|
+
onMessage.call(self, msg);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
this.dispatchEvent(new yaeti.Event('open'));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
function onConnectFailed() {
|
|
213
|
+
destroy.call(this);
|
|
214
|
+
this._readyState = CLOSED;
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
this.dispatchEvent(new yaeti.Event('error'));
|
|
218
|
+
} finally {
|
|
219
|
+
this.dispatchEvent(createCloseEvent(1006, 'connection failed'));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
function onClose(code, reason) {
|
|
225
|
+
destroy.call(this);
|
|
226
|
+
this._readyState = CLOSED;
|
|
227
|
+
|
|
228
|
+
this.dispatchEvent(createCloseEvent(code, reason || ''));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
function onMessage(message) {
|
|
233
|
+
if (message.utf8Data) {
|
|
234
|
+
this.dispatchEvent(createMessageEvent(message.utf8Data));
|
|
235
|
+
}
|
|
236
|
+
else if (message.binaryData) {
|
|
237
|
+
// Must convert from Node Buffer to ArrayBuffer.
|
|
238
|
+
// TODO: or to a Blob (which does not exist in Node!).
|
|
239
|
+
if (this.binaryType === 'arraybuffer') {
|
|
240
|
+
var buffer = message.binaryData;
|
|
241
|
+
var arraybuffer = new ArrayBuffer(buffer.length);
|
|
242
|
+
var view = new Uint8Array(arraybuffer);
|
|
243
|
+
for (var i=0, len=buffer.length; i<len; ++i) {
|
|
244
|
+
view[i] = buffer[i];
|
|
245
|
+
}
|
|
246
|
+
this.dispatchEvent(createMessageEvent(arraybuffer));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
function destroy() {
|
|
253
|
+
this._client.removeAllListeners();
|
|
254
|
+
if (this._connection) {
|
|
255
|
+
this._connection.removeAllListeners();
|
|
256
|
+
}
|
|
257
|
+
}
|