README.md (7119B)
1# ws: a node.js websocket library 2 3[![Build Status](https://travis-ci.org/websockets/ws.svg?branch=master)](https://travis-ci.org/websockets/ws) 4 5`ws` is a simple to use WebSocket implementation, up-to-date against RFC-6455, 6and [probably the fastest WebSocket library for node.js][archive]. 7 8Passes the quite extensive Autobahn test suite. See http://websockets.github.com/ws 9for the full reports. 10 11## Protocol support 12 13* **Hixie draft 76** (Old and deprecated, but still in use by Safari and Opera. 14 Added to ws version 0.4.2, but server only. Can be disabled by setting the 15 `disableHixie` option to true.) 16* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) 17* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) 18 19### Installing 20 21``` 22npm install --save ws 23``` 24 25### Opt-in for performance 26 27There are 2 optional modules that can be installed along side with the `ws` 28module. These modules are binary addons which improve certain operations, but as 29they are binary addons they require compilation which can fail if no c++ 30compiler is installed on the host system. 31 32- `npm install --save bufferutil`: Improves internal buffer operations which 33 allows for faster processing of masked WebSocket frames and general buffer 34 operations. 35- `npm install --save utf-8-validate`: The specification requires validation of 36 invalid UTF-8 chars, some of these validations could not be done in JavaScript 37 hence the need for a binary addon. In most cases you will already be 38 validating the input that you receive for security purposes leading to double 39 validation. But if you want to be 100% spec-conforming and have fast 40 validation of UTF-8 then this module is a must. 41 42### Sending and receiving text data 43 44```js 45var WebSocket = require('ws'); 46var ws = new WebSocket('ws://www.host.com/path'); 47 48ws.on('open', function open() { 49 ws.send('something'); 50}); 51 52ws.on('message', function(data, flags) { 53 // flags.binary will be set if a binary data is received. 54 // flags.masked will be set if the data was masked. 55}); 56``` 57 58### Sending binary data 59 60```js 61var WebSocket = require('ws'); 62var ws = new WebSocket('ws://www.host.com/path'); 63 64ws.on('open', function open() { 65 var array = new Float32Array(5); 66 67 for (var i = 0; i < array.length; ++i) { 68 array[i] = i / 2; 69 } 70 71 ws.send(array, { binary: true, mask: true }); 72}); 73``` 74 75Setting `mask`, as done for the send options above, will cause the data to be 76masked according to the WebSocket protocol. The same option applies for text 77data. 78 79### Server example 80 81```js 82var WebSocketServer = require('ws').Server 83 , wss = new WebSocketServer({ port: 8080 }); 84 85wss.on('connection', function connection(ws) { 86 ws.on('message', function incoming(message) { 87 console.log('received: %s', message); 88 }); 89 90 ws.send('something'); 91}); 92``` 93 94### ExpressJS example 95 96```js 97var server = require('http').createServer() 98 , url = require('url') 99 , WebSocketServer = require('ws').Server 100 , wss = new WebSocketServer({ server: server }) 101 , express = require('express') 102 , app = express() 103 , port = 4080; 104 105app.use(function (req, res) { 106 res.send({ msg: "hello" }); 107}); 108 109wss.on('connection', function connection(ws) { 110 var location = url.parse(ws.upgradeReq.url, true); 111 // you might use location.query.access_token to authenticate or share sessions 112 // or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312) 113 114 ws.on('message', function incoming(message) { 115 console.log('received: %s', message); 116 }); 117 118 ws.send('something'); 119}); 120 121server.on('request', app); 122server.listen(port, function () { console.log('Listening on ' + server.address().port) }); 123``` 124 125### Server sending broadcast data 126 127```js 128var WebSocketServer = require('ws').Server 129 , wss = new WebSocketServer({ port: 8080 }); 130 131wss.broadcast = function broadcast(data) { 132 wss.clients.forEach(function each(client) { 133 client.send(data); 134 }); 135}; 136``` 137 138### Error handling best practices 139 140```js 141// If the WebSocket is closed before the following send is attempted 142ws.send('something'); 143 144// Errors (both immediate and async write errors) can be detected in an optional 145// callback. The callback is also the only way of being notified that data has 146// actually been sent. 147ws.send('something', function ack(error) { 148 // if error is not defined, the send has been completed, 149 // otherwise the error object will indicate what failed. 150}); 151 152// Immediate errors can also be handled with try/catch-blocks, but **note** that 153// since sends are inherently asynchronous, socket write failures will *not* be 154// captured when this technique is used. 155try { ws.send('something'); } 156catch (e) { /* handle error */ } 157``` 158 159### echo.websocket.org demo 160 161```js 162var WebSocket = require('ws'); 163var ws = new WebSocket('ws://echo.websocket.org/', { 164 protocolVersion: 8, 165 origin: 'http://websocket.org' 166}); 167 168ws.on('open', function open() { 169 console.log('connected'); 170 ws.send(Date.now().toString(), {mask: true}); 171}); 172 173ws.on('close', function close() { 174 console.log('disconnected'); 175}); 176 177ws.on('message', function message(data, flags) { 178 console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); 179 180 setTimeout(function timeout() { 181 ws.send(Date.now().toString(), {mask: true}); 182 }, 500); 183}); 184``` 185 186### Other examples 187 188For a full example with a browser client communicating with a ws server, see the 189examples folder. 190 191Note that the usage together with Express 3.0 is quite different from Express 1922.x. The difference is expressed in the two different serverstats-examples. 193 194Otherwise, see the test cases. 195 196### Running the tests 197 198``` 199make test 200``` 201 202## API Docs 203 204See [`/doc/ws.md`](https://github.com/websockets/ws/blob/master/doc/ws.md) for Node.js-like docs for the ws classes. 205 206## Changelog 207 208We're using the GitHub [`releases`](https://github.com/websockets/ws/releases) for changelog entries. 209 210## License 211 212(The MIT License) 213 214Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com> 215 216Permission is hereby granted, free of charge, to any person obtaining 217a copy of this software and associated documentation files (the 218'Software'), to deal in the Software without restriction, including 219without limitation the rights to use, copy, modify, merge, publish, 220distribute, sublicense, and/or sell copies of the Software, and to 221permit persons to whom the Software is furnished to do so, subject to 222the following conditions: 223 224The above copyright notice and this permission notice shall be 225included in all copies or substantial portions of the Software. 226 227THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 228EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 229MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 230IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 231CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 232TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 233SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 234 235[archive]: http://web.archive.org/web/20130314230536/http://hobbycoding.posterous.com/the-fastest-websocket-module-for-nodejs