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### Sending and receiving text data 26 27```js 28var WebSocket = require('ws'); 29var ws = new WebSocket('ws://www.host.com/path'); 30 31ws.on('open', function open() { 32 ws.send('something'); 33}); 34 35ws.on('message', function(data, flags) { 36 // flags.binary will be set if a binary data is received. 37 // flags.masked will be set if the data was masked. 38}); 39``` 40 41### Sending binary data 42 43```js 44var WebSocket = require('ws'); 45var ws = new WebSocket('ws://www.host.com/path'); 46 47ws.on('open', function open() { 48 var array = new Float32Array(5); 49 50 for (var i = 0; i < array.length; ++i) { 51 array[i] = i / 2; 52 } 53 54 ws.send(array, { binary: true, mask: true }); 55}); 56``` 57 58Setting `mask`, as done for the send options above, will cause the data to be 59masked according to the WebSocket protocol. The same option applies for text 60data. 61 62### Server example 63 64```js 65var WebSocketServer = require('ws').Server 66 , wss = new WebSocketServer({ port: 8080 }); 67 68wss.on('connection', function connection(ws) { 69 ws.on('message', function incoming(message) { 70 console.log('received: %s', message); 71 }); 72 73 ws.send('something'); 74}); 75``` 76 77### ExpressJS example 78 79```js 80var server = require('http').createServer() 81 , url = require('url') 82 , WebSocketServer = require('ws').Server 83 , wss = new WebSocketServer({ server: server }) 84 , express = require('express') 85 , app = express() 86 , port = 4080; 87 88app.use(function (req, res) { 89 res.send({ msg: "hello" }); 90}); 91 92wss.on('connection', function connection(ws) { 93 var location = url.parse(ws.upgradeReq.url, true); 94 // you might use location.query.access_token to authenticate or share sessions 95 // or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312) 96 97 ws.on('message', function incoming(message) { 98 console.log('received: %s', message); 99 }); 100 101 ws.send('something'); 102}); 103 104server.on('request', app); 105server.listen(port, function () { console.log('Listening on ' + server.address().port) }); 106``` 107 108### Server sending broadcast data 109 110```js 111var WebSocketServer = require('ws').Server 112 , wss = new WebSocketServer({ port: 8080 }); 113 114wss.broadcast = function broadcast(data) { 115 wss.clients.forEach(function each(client) { 116 client.send(data); 117 }); 118}; 119``` 120 121### Error handling best practices 122 123```js 124// If the WebSocket is closed before the following send is attempted 125ws.send('something'); 126 127// Errors (both immediate and async write errors) can be detected in an optional 128// callback. The callback is also the only way of being notified that data has 129// actually been sent. 130ws.send('something', function ack(error) { 131 // if error is not defined, the send has been completed, 132 // otherwise the error object will indicate what failed. 133}); 134 135// Immediate errors can also be handled with try/catch-blocks, but **note** that 136// since sends are inherently asynchronous, socket write failures will *not* be 137// captured when this technique is used. 138try { ws.send('something'); } 139catch (e) { /* handle error */ } 140``` 141 142### echo.websocket.org demo 143 144```js 145var WebSocket = require('ws'); 146var ws = new WebSocket('ws://echo.websocket.org/', { 147 protocolVersion: 8, 148 origin: 'http://websocket.org' 149}); 150 151ws.on('open', function open() { 152 console.log('connected'); 153 ws.send(Date.now().toString(), {mask: true}); 154}); 155 156ws.on('close', function close() { 157 console.log('disconnected'); 158}); 159 160ws.on('message', function message(data, flags) { 161 console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags); 162 163 setTimeout(function timeout() { 164 ws.send(Date.now().toString(), {mask: true}); 165 }, 500); 166}); 167``` 168 169### Browserify users 170When including ws via a browserify bundle, ws returns global.WebSocket which has slightly different API. 171You should use the standard WebSockets API instead. 172 173https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications#Availability_of_WebSockets 174 175 176### Other examples 177 178For a full example with a browser client communicating with a ws server, see the 179examples folder. 180 181Note that the usage together with Express 3.0 is quite different from Express 1822.x. The difference is expressed in the two different serverstats-examples. 183 184Otherwise, see the test cases. 185 186### Running the tests 187 188``` 189make test 190``` 191 192## API Docs 193 194See [`/doc/ws.md`](https://github.com/websockets/ws/blob/master/doc/ws.md) for Node.js-like docs for the ws classes. 195 196## Changelog 197 198We're using the GitHub [`releases`](https://github.com/websockets/ws/releases) for changelog entries. 199 200## License 201 202(The MIT License) 203 204Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com> 205 206Permission is hereby granted, free of charge, to any person obtaining 207a copy of this software and associated documentation files (the 208'Software'), to deal in the Software without restriction, including 209without limitation the rights to use, copy, modify, merge, publish, 210distribute, sublicense, and/or sell copies of the Software, and to 211permit persons to whom the Software is furnished to do so, subject to 212the following conditions: 213 214The above copyright notice and this permission notice shall be 215included in all copies or substantial portions of the Software. 216 217THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 218EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 219MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 220IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 221CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 222TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 223SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 224 225[archive]: http://web.archive.org/web/20130314230536/http://hobbycoding.posterous.com/the-fastest-websocket-module-for-nodejs 226