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.

336 lines
12 KiB

4 years ago
  1. # faye-websocket
  2. * Travis CI build: [![Build
  3. status](https://secure.travis-ci.org/faye/faye-websocket-node.svg)](http://travis-ci.org/faye/faye-websocket-node)
  4. * Autobahn tests: [server](http://faye.jcoglan.com/autobahn/servers/),
  5. [client](http://faye.jcoglan.com/autobahn/clients/)
  6. This is a general-purpose WebSocket implementation extracted from the
  7. [Faye](http://faye.jcoglan.com) project. It provides classes for easily building
  8. WebSocket servers and clients in Node. It does not provide a server itself, but
  9. rather makes it easy to handle WebSocket connections within an existing
  10. [Node](http://nodejs.org/) application. It does not provide any abstraction
  11. other than the standard [WebSocket API](http://dev.w3.org/html5/websockets/).
  12. It also provides an abstraction for handling
  13. [EventSource](http://dev.w3.org/html5/eventsource/) connections, which are
  14. one-way connections that allow the server to push data to the client. They are
  15. based on streaming HTTP responses and can be easier to access via proxies than
  16. WebSockets.
  17. ## Installation
  18. ```
  19. $ npm install faye-websocket
  20. ```
  21. ## Handling WebSocket connections in Node
  22. You can handle WebSockets on the server side by listening for HTTP Upgrade
  23. requests, and creating a new socket for the request. This socket object exposes
  24. the usual WebSocket methods for receiving and sending messages. For example this
  25. is how you'd implement an echo server:
  26. ```js
  27. var WebSocket = require('faye-websocket'),
  28. http = require('http');
  29. var server = http.createServer();
  30. server.on('upgrade', function(request, socket, body) {
  31. if (WebSocket.isWebSocket(request)) {
  32. var ws = new WebSocket(request, socket, body);
  33. ws.on('message', function(event) {
  34. ws.send(event.data);
  35. });
  36. ws.on('close', function(event) {
  37. console.log('close', event.code, event.reason);
  38. ws = null;
  39. });
  40. }
  41. });
  42. server.listen(8000);
  43. ```
  44. `WebSocket` objects are also duplex streams, so you could replace the
  45. `ws.on('message', ...)` line with:
  46. ```js
  47. ws.pipe(ws);
  48. ```
  49. Note that under certain circumstances (notably a draft-76 client connecting
  50. through an HTTP proxy), the WebSocket handshake will not be complete after you
  51. call `new WebSocket()` because the server will not have received the entire
  52. handshake from the client yet. In this case, calls to `ws.send()` will buffer
  53. the message in memory until the handshake is complete, at which point any
  54. buffered messages will be sent to the client.
  55. If you need to detect when the WebSocket handshake is complete, you can use the
  56. `onopen` event.
  57. If the connection's protocol version supports it, you can call `ws.ping()` to
  58. send a ping message and wait for the client's response. This method takes a
  59. message string, and an optional callback that fires when a matching pong message
  60. is received. It returns `true` if and only if a ping message was sent. If the
  61. client does not support ping/pong, this method sends no data and returns
  62. `false`.
  63. ```js
  64. ws.ping('Mic check, one, two', function() {
  65. // fires when pong is received
  66. });
  67. ```
  68. ## Using the WebSocket client
  69. The client supports both the plain-text `ws` protocol and the encrypted `wss`
  70. protocol, and has exactly the same interface as a socket you would use in a web
  71. browser. On the wire it identifies itself as `hybi-13`.
  72. ```js
  73. var WebSocket = require('faye-websocket'),
  74. ws = new WebSocket.Client('ws://www.example.com/');
  75. ws.on('open', function(event) {
  76. console.log('open');
  77. ws.send('Hello, world!');
  78. });
  79. ws.on('message', function(event) {
  80. console.log('message', event.data);
  81. });
  82. ws.on('close', function(event) {
  83. console.log('close', event.code, event.reason);
  84. ws = null;
  85. });
  86. ```
  87. The WebSocket client also lets you inspect the status and headers of the
  88. handshake response via its `statusCode` and `headers` properties.
  89. To connect via a proxy, set the `proxy` option to the HTTP origin of the proxy,
  90. including any authorization information, custom headers and TLS config you
  91. require. Only the `origin` setting is required.
  92. ```js
  93. var ws = new WebSocket.Client('ws://www.example.com/', [], {
  94. proxy: {
  95. origin: 'http://username:password@proxy.example.com',
  96. headers: {'User-Agent': 'node'},
  97. tls: {cert: fs.readFileSync('client.crt')}
  98. }
  99. });
  100. ```
  101. The `tls` value is a Node 'TLS options' object that will be passed to
  102. [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
  103. ## Subprotocol negotiation
  104. The WebSocket protocol allows peers to select and identify the application
  105. protocol to use over the connection. On the client side, you can set which
  106. protocols the client accepts by passing a list of protocol names when you
  107. construct the socket:
  108. ```js
  109. var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']);
  110. ```
  111. On the server side, you can likewise pass in the list of protocols the server
  112. supports after the other constructor arguments:
  113. ```js
  114. var ws = new WebSocket(request, socket, body, ['irc', 'amqp']);
  115. ```
  116. If the client and server agree on a protocol, both the client- and server-side
  117. socket objects expose the selected protocol through the `ws.protocol` property.
  118. ## Protocol extensions
  119. faye-websocket is based on the
  120. [websocket-extensions](https://github.com/faye/websocket-extensions-node)
  121. framework that allows extensions to be negotiated via the
  122. `Sec-WebSocket-Extensions` header. To add extensions to a connection, pass an
  123. array of extensions to the `:extensions` option. For example, to add
  124. [permessage-deflate](https://github.com/faye/permessage-deflate-node):
  125. ```js
  126. var deflate = require('permessage-deflate');
  127. var ws = new WebSocket(request, socket, body, [], {extensions: [deflate]});
  128. ```
  129. ## Initialization options
  130. Both the server- and client-side classes allow an options object to be passed in
  131. at initialization time, for example:
  132. ```js
  133. var ws = new WebSocket(request, socket, body, protocols, options);
  134. var ws = new WebSocket.Client(url, protocols, options);
  135. ```
  136. `protocols` is an array of subprotocols as described above, or `null`.
  137. `options` is an optional object containing any of these fields:
  138. * `extensions` - an array of
  139. [websocket-extensions](https://github.com/faye/websocket-extensions-node)
  140. compatible extensions, as described above
  141. * `headers` - an object containing key-value pairs representing HTTP headers to
  142. be sent during the handshake process
  143. * `maxLength` - the maximum allowed size of incoming message frames, in bytes.
  144. The default value is `2^26 - 1`, or 1 byte short of 64 MiB.
  145. * `ping` - an integer that sets how often the WebSocket should send ping frames,
  146. measured in seconds
  147. The client accepts some additional options:
  148. * `proxy` - settings for a proxy as described above
  149. * `tls` - a Node 'TLS options' object containing TLS settings for the origin
  150. server, this will be passed to
  151. [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
  152. * `ca` - (legacy) a shorthand for passing `{tls: {ca: value}}`
  153. ## WebSocket API
  154. Both server- and client-side `WebSocket` objects support the following API.
  155. * <b>`on('open', function(event) {})`</b> fires when the socket connection is
  156. established. Event has no attributes.
  157. * <b>`on('message', function(event) {})`</b> fires when the socket receives a
  158. message. Event has one attribute, <b>`data`</b>, which is either a `String`
  159. (for text frames) or a `Buffer` (for binary frames).
  160. * <b>`on('error', function(event) {})`</b> fires when there is a protocol error
  161. due to bad data sent by the other peer. This event is purely informational,
  162. you do not need to implement error recover.
  163. * <b>`on('close', function(event) {})`</b> fires when either the client or the
  164. server closes the connection. Event has two optional attributes, <b>`code`</b>
  165. and <b>`reason`</b>, that expose the status code and message sent by the peer
  166. that closed the connection.
  167. * <b>`send(message)`</b> accepts either a `String` or a `Buffer` and sends a
  168. text or binary message over the connection to the other peer.
  169. * <b>`ping(message, function() {})`</b> sends a ping frame with an optional
  170. message and fires the callback when a matching pong is received.
  171. * <b>`close(code, reason)`</b> closes the connection, sending the given status
  172. code and reason text, both of which are optional.
  173. * <b>`version`</b> is a string containing the version of the `WebSocket`
  174. protocol the connection is using.
  175. * <b>`protocol`</b> is a string (which may be empty) identifying the subprotocol
  176. the socket is using.
  177. ## Handling EventSource connections in Node
  178. EventSource connections provide a very similar interface, although because they
  179. only allow the server to send data to the client, there is no `onmessage` API.
  180. EventSource allows the server to push text messages to the client, where each
  181. message has an optional event-type and ID.
  182. ```js
  183. var WebSocket = require('faye-websocket'),
  184. EventSource = WebSocket.EventSource,
  185. http = require('http');
  186. var server = http.createServer();
  187. server.on('request', function(request, response) {
  188. if (EventSource.isEventSource(request)) {
  189. var es = new EventSource(request, response);
  190. console.log('open', es.url, es.lastEventId);
  191. // Periodically send messages
  192. var loop = setInterval(function() { es.send('Hello') }, 1000);
  193. es.on('close', function() {
  194. clearInterval(loop);
  195. es = null;
  196. });
  197. } else {
  198. // Normal HTTP request
  199. response.writeHead(200, {'Content-Type': 'text/plain'});
  200. response.end('Hello');
  201. }
  202. });
  203. server.listen(8000);
  204. ```
  205. The `send` method takes two optional parameters, `event` and `id`. The default
  206. event-type is `'message'` with no ID. For example, to send a `notification`
  207. event with ID `99`:
  208. ```js
  209. es.send('Breaking News!', {event: 'notification', id: '99'});
  210. ```
  211. The `EventSource` object exposes the following properties:
  212. * <b>`url`</b> is a string containing the URL the client used to create the
  213. EventSource.
  214. * <b>`lastEventId`</b> is a string containing the last event ID received by the
  215. client. You can use this when the client reconnects after a dropped connection
  216. to determine which messages need resending.
  217. When you initialize an EventSource with ` new EventSource()`, you can pass
  218. configuration options after the `response` parameter. Available options are:
  219. * <b>`headers`</b> is an object containing custom headers to be set on the
  220. EventSource response.
  221. * <b>`retry`</b> is a number that tells the client how long (in seconds) it
  222. should wait after a dropped connection before attempting to reconnect.
  223. * <b>`ping`</b> is a number that tells the server how often (in seconds) to send
  224. 'ping' packets to the client to keep the connection open, to defeat timeouts
  225. set by proxies. The client will ignore these messages.
  226. For example, this creates a connection that allows access from any origin, pings
  227. every 15 seconds and is retryable every 10 seconds if the connection is broken:
  228. ```js
  229. var es = new EventSource(request, response, {
  230. headers: {'Access-Control-Allow-Origin': '*'},
  231. ping: 15,
  232. retry: 10
  233. });
  234. ```
  235. You can send a ping message at any time by calling `es.ping()`. Unlike
  236. WebSocket, the client does not send a response to this; it is merely to send
  237. some data over the wire to keep the connection alive.
  238. ## License
  239. (The MIT License)
  240. Copyright (c) 2010-2015 James Coglan
  241. Permission is hereby granted, free of charge, to any person obtaining a copy of
  242. this software and associated documentation files (the 'Software'), to deal in
  243. the Software without restriction, including without limitation the rights to
  244. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  245. the Software, and to permit persons to whom the Software is furnished to do so,
  246. subject to the following conditions:
  247. The above copyright notice and this permission notice shall be included in all
  248. copies or substantial portions of the Software.
  249. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  250. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  251. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  252. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  253. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  254. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.