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.

171 lines
5.5 KiB

  1. [![Build Status](https://secure.travis-ci.org/einaros/ws.png)](http://travis-ci.org/einaros/ws)
  2. # ws: a node.js websocket library #
  3. `ws` is a simple to use websocket implementation, up-to-date against RFC-6455, and [probably the fastest WebSocket library for node.js](http://web.archive.org/web/20130314230536/http://hobbycoding.posterous.com/the-fastest-websocket-module-for-nodejs).
  4. Passes the quite extensive Autobahn test suite. See http://einaros.github.com/ws for the full reports.
  5. Comes with a command line utility, `wscat`, which can either act as a server (--listen), or client (--connect); Use it to debug simple websocket services.
  6. ## Protocol support ##
  7. * **Hixie draft 76** (Old and deprecated, but still in use by Safari and Opera. Added to ws version 0.4.2, but server only. Can be disabled by setting the `disableHixie` option to true.)
  8. * **HyBi drafts 07-12** (Use the option `protocolVersion: 8`, or argument `-p 8` for wscat)
  9. * **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`, or argument `-p 13` for wscat)
  10. _See the echo.websocket.org example below for how to use the `protocolVersion` option._
  11. ## Usage ##
  12. ### Installing ###
  13. `npm install ws`
  14. ### Sending and receiving text data ###
  15. ```js
  16. var WebSocket = require('ws');
  17. var ws = new WebSocket('ws://www.host.com/path');
  18. ws.on('open', function() {
  19. ws.send('something');
  20. });
  21. ws.on('message', function(data, flags) {
  22. // flags.binary will be set if a binary data is received
  23. // flags.masked will be set if the data was masked
  24. });
  25. ```
  26. ### Sending binary data ###
  27. ```js
  28. var WebSocket = require('ws');
  29. var ws = new WebSocket('ws://www.host.com/path');
  30. ws.on('open', function() {
  31. var array = new Float32Array(5);
  32. for (var i = 0; i < array.length; ++i) array[i] = i / 2;
  33. ws.send(array, {binary: true, mask: true});
  34. });
  35. ```
  36. Setting `mask`, as done for the send options above, will cause the data to be masked according to the websocket protocol. The same option applies for text data.
  37. ### Server example ###
  38. ```js
  39. var WebSocketServer = require('ws').Server
  40. , wss = new WebSocketServer({port: 8080});
  41. wss.on('connection', function(ws) {
  42. ws.on('message', function(message) {
  43. console.log('received: %s', message);
  44. });
  45. ws.send('something');
  46. });
  47. ```
  48. ### Server sending broadcast data ###
  49. ```js
  50. var WebSocketServer = require('ws').Server
  51. , wss = new WebSocketServer({port: 8080});
  52. wss.broadcast = function(data) {
  53. for(var i in this.clients)
  54. this.clients[i].send(data);
  55. };
  56. ```
  57. ### Error handling best practices ###
  58. ```js
  59. // If the WebSocket is closed before the following send is attempted
  60. ws.send('something');
  61. // Errors (both immediate and async write errors) can be detected in an optional callback.
  62. // The callback is also the only way of being notified that data has actually been sent.
  63. ws.send('something', function(error) {
  64. // if error is null, the send has been completed,
  65. // otherwise the error object will indicate what failed.
  66. });
  67. // Immediate errors can also be handled with try/catch-blocks, but **note**
  68. // that since sends are inherently asynchronous, socket write failures will *not*
  69. // be captured when this technique is used.
  70. try {
  71. ws.send('something');
  72. }
  73. catch (e) {
  74. // handle error
  75. }
  76. ```
  77. ### echo.websocket.org demo ###
  78. ```js
  79. var WebSocket = require('ws');
  80. var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
  81. ws.on('open', function() {
  82. console.log('connected');
  83. ws.send(Date.now().toString(), {mask: true});
  84. });
  85. ws.on('close', function() {
  86. console.log('disconnected');
  87. });
  88. ws.on('message', function(data, flags) {
  89. console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags);
  90. setTimeout(function() {
  91. ws.send(Date.now().toString(), {mask: true});
  92. }, 500);
  93. });
  94. ```
  95. ### wscat against echo.websocket.org ###
  96. $ npm install -g ws
  97. $ wscat -c ws://echo.websocket.org -p 8
  98. connected (press CTRL+C to quit)
  99. > hi there
  100. < hi there
  101. > are you a happy parrot?
  102. < are you a happy parrot?
  103. ### Other examples ###
  104. For a full example with a browser client communicating with a ws server, see the examples folder.
  105. Note that the usage together with Express 3.0 is quite different from Express 2.x. The difference is expressed in the two different serverstats-examples.
  106. Otherwise, see the test cases.
  107. ### Running the tests ###
  108. `make test`
  109. ## API Docs ##
  110. See the doc/ directory for Node.js-like docs for the ws classes.
  111. ## License ##
  112. (The MIT License)
  113. Copyright (c) 2011 Einar Otto Stangvik &lt;einaros@gmail.com&gt;
  114. Permission is hereby granted, free of charge, to any person obtaining
  115. a copy of this software and associated documentation files (the
  116. 'Software'), to deal in the Software without restriction, including
  117. without limitation the rights to use, copy, modify, merge, publish,
  118. distribute, sublicense, and/or sell copies of the Software, and to
  119. permit persons to whom the Software is furnished to do so, subject to
  120. the following conditions:
  121. The above copyright notice and this permission notice shall be
  122. included in all copies or substantial portions of the Software.
  123. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  124. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  125. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  126. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  127. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  128. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  129. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.