initial commit
[JIRC.git] / node_modules / websocket / README.md
1 WebSocket Client & Server Implementation for Node
2 =================================================
3
4 Overview
5 --------
6 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" folder.
7
8 Current News
9 ------------
10
11 - As of version 1.0.7, ***Native modules are now optional.*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code.
12
13 - Version 1.0.7 requires node v0.6.10, since that's the first version that I can manage to successfully build the native extensions with node-gyp through npm. If anyone can figure out how to build native extensions in a way that works with both older and newer versions of Node, I'm happy to accept a patch!
14
15 - If you want to support Unicode characters outside the Basic Multilingual Plane (BMP) you must use Node v0.8.x, which added support for representing these characters as surrogate pairs inside JavaScript strings. Under Node v0.6.x, characters with code points greater than 65535 (greater than a 16-bit unsigned value) will have their code point truncated, resulting in seemingly unpredictable characters being returned.
16
17 - WebSocket-Node was already [one of the fastest WebSocket libraries for Node](http://hobbycoding.posterous.com/websockt-binary-data-transfer-benchmark-rsult), and thanks to a small patch from [kazuyukitanimura](https://github.com/kazuyukitanimura), this library is now [up to 200% faster](http://hobbycoding.posterous.com/how-to-make-websocket-work-2x-faster-on-nodej) as of version 1.0.3!
18
19 Changelog
20 ---------
21
22 Current Version: 1.0.7
23
24 [View the changelog](https://github.com/Worlize/WebSocket-Node/blob/master/CHANGELOG.md)
25
26 Browser Support
27 ---------------
28
29 * Firefox 7-9 (Old) (Protocol Version 8)
30 * Firefox 10+ (Protocol Version 13)
31 * Chrome 14,15 (Old) (Protocol Version 8)
32 * Chrome 16+ (Protocol Version 13)
33 * Internet Explorer 10 (Preview) (Protocol Version 13)
34 * Safari 6 (Protocol Version 13)
35
36 ***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets***
37
38 I made a decision early on to explicitly avoid maintaining multiple slightly different copies of the same code just to support the browsers currently in the wild. The major browsers that support WebSocket are on a rapid-release schedule (with the exception of Safari) and now that the final version of the protocol has been [published as an official RFC](http://datatracker.ietf.org/doc/rfc6455/), it won't be long before support in the wild stabilizes on that version. My client application is in Flash/ActionScript 3, so for my purposes I'm not dependent on the browser implementations. *I made an exception to my stated intention here to support protocol version 8 along with 13, since only one minor thing changed and it was trivial to handle conditionally.* The library now interoperates with other clients and servers implementing draft -08 all the way up through the final RFC.
39
40 ***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579***
41
42 For a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/Worlize/AS3WebSocket) project.
43
44 Benchmarks
45 ----------
46 There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://worlize.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 Autobahn Tests
49 --------------
50 The very complete [Autobahn Test Suite](http://www.tavendo.de/autobahn/testsuite.html) is used by most WebSocket implementations to test spec compliance and interoperability.
51
52 **Note about failing UTF-8 tests:** There are some UTF-8 validation tests that fail due to the fact that according to the ECMAScript spec, V8 and subsequently Node cannot support Unicode characters outside the BMP (Basic Multilingual Plane.) JavaScript's String.fromCharCode() function truncates all code points to 16-bit, so you cannot decode higher plane code points in JavaScript. Google's V8 uses UCS-2 as its internal string representation, and [they have no intention to change that any time soon](http://code.google.com/p/v8/issues/detail?id=761), so it is not possible to decode higher plane code points in C++, to the best of my knowledge, because those characters are not representable in UCS-2 anyway. The Autobahn Test Suite requires that all valid Unicode code points survive a complete round trip, including code points that represent non-existent characters and characters above the BMP. Since JavaScript cannot represent any characters with a code point >= 65535, no JavaScript implementation of WebSockets can pass these UTF-8 tests without using a cheat, such as echoing back the original binary data without decoding and re-encoding the UTF-8 data, which is not representative of real-world practical application. ***I do not consider this to be a problem in the majority of circumstances*** since it is very unlikely to cause major issues in any real-world application as long as you don't need to use characters outside the BMP.
53 **Update:** This issue seems to have been resolved in the version of V8 used in Node 0.8.x. I believe they are using surrogate-pairs to accommodate characters that are outside the BMP, but I haven't looked into it.
54
55 - [View Server Test Results](http://worlize.github.com/WebSocket-Node/test-report/servers/)
56 - [View Client Test Results](http://worlize.github.com/WebSocket-Node/test-report/clients/)
57
58 Notes
59 -----
60 This library has been used in production on [worlize.com](https://www.worlize.com) since April 2011 and seems to be stable. Your mileage may vary.
61
62 **Tested with the following node versions:**
63
64 - 0.6.18
65 - 0.8.6
66
67 It may work in earlier or later versions but I'm not actively testing it outside of the listed versions. YMMV.
68
69 Documentation
70 =============
71
72 For more complete documentation, see the [Documentation Wiki](https://github.com/Worlize/WebSocket-Node/wiki/Documentation).
73
74 Installation
75 ------------
76 In your project root:
77
78 $ npm install websocket
79
80 Then in your code:
81
82 ```javascript
83 var WebSocketServer = require('websocket').server;
84 var WebSocketClient = require('websocket').client;
85 var WebSocketFrame = require('websocket').frame;
86 var WebSocketRouter = require('websocket').router;
87 ```
88
89 Note for Windows Users
90 ----------------------
91 Because there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module:
92
93 - [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)
94 - [Python 2.7](http://www.python.org/download/) (NOT Python 3.x)
95
96
97 Current Features:
98 -----------------
99 - Licensed under the Apache License, Version 2.0
100 - Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
101 - Can handle/aggregate received fragmented messages
102 - Can fragment outgoing messages
103 - Router to mount multiple applications to various path and protocol combinations
104 - TLS supported for outbound connections via WebSocketClient
105 - TLS supported for server connections (use https.createServer instead of http.createServer)
106 - Thanks to [pors](https://github.com/pors) for confirming this!
107 - Cookie setting and parsing
108 - Tunable settings
109 - Max Receivable Frame Size
110 - Max Aggregate ReceivedMessage Size
111 - Whether to fragment outgoing messages
112 - Fragmentation chunk size for outgoing messages
113 - Whether to automatically send ping frames for the purposes of keepalive
114 - Keep-alive ping interval
115 - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
116 - How long to wait after sending a close frame for acknowledgment before closing the socket.
117
118
119 Known Issues/Missing Features:
120 ------------------------------
121 - No API for user-provided protocol extensions.
122
123
124 Usage Examples
125 ==============
126
127 Server Example
128 --------------
129
130 Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
131
132 ```javascript
133 #!/usr/bin/env node
134 var WebSocketServer = require('websocket').server;
135 var http = require('http');
136
137 var server = http.createServer(function(request, response) {
138 console.log((new Date()) + ' Received request for ' + request.url);
139 response.writeHead(404);
140 response.end();
141 });
142 server.listen(8080, function() {
143 console.log((new Date()) + ' Server is listening on port 8080');
144 });
145
146 wsServer = new WebSocketServer({
147 httpServer: server,
148 // You should not use autoAcceptConnections for production
149 // applications, as it defeats all standard cross-origin protection
150 // facilities built into the protocol and the browser. You should
151 // *always* verify the connection's origin and decide whether or not
152 // to accept it.
153 autoAcceptConnections: false
154 });
155
156 function originIsAllowed(origin) {
157 // put logic here to detect whether the specified origin is allowed.
158 return true;
159 }
160
161 wsServer.on('request', function(request) {
162 if (!originIsAllowed(request.origin)) {
163 // Make sure we only accept requests from an allowed origin
164 request.reject();
165 console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
166 return;
167 }
168
169 var connection = request.accept('echo-protocol', request.origin);
170 console.log((new Date()) + ' Connection accepted.');
171 connection.on('message', function(message) {
172 if (message.type === 'utf8') {
173 console.log('Received Message: ' + message.utf8Data);
174 connection.sendUTF(message.utf8Data);
175 }
176 else if (message.type === 'binary') {
177 console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
178 connection.sendBytes(message.binaryData);
179 }
180 });
181 connection.on('close', function(reasonCode, description) {
182 console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
183 });
184 });
185 ```
186
187 Client Example
188 --------------
189
190 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.
191
192 *This code demonstrates a client in Node.js, not in the browser*
193
194 ```javascript
195 #!/usr/bin/env node
196 var WebSocketClient = require('websocket').client;
197
198 var client = new WebSocketClient();
199
200 client.on('connectFailed', function(error) {
201 console.log('Connect Error: ' + error.toString());
202 });
203
204 client.on('connect', function(connection) {
205 console.log('WebSocket client connected');
206 connection.on('error', function(error) {
207 console.log("Connection Error: " + error.toString());
208 });
209 connection.on('close', function() {
210 console.log('echo-protocol Connection Closed');
211 });
212 connection.on('message', function(message) {
213 if (message.type === 'utf8') {
214 console.log("Received: '" + message.utf8Data + "'");
215 }
216 });
217
218 function sendNumber() {
219 if (connection.connected) {
220 var number = Math.round(Math.random() * 0xFFFFFF);
221 connection.sendUTF(number.toString());
222 setTimeout(sendNumber, 1000);
223 }
224 }
225 sendNumber();
226 });
227
228 client.connect('ws://localhost:8080/', 'echo-protocol');
229 ```
230
231 Request Router Example
232 ----------------------
233
234 For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.
235
236
237 Resources
238 ---------
239
240 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)