You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
7.0 KiB

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