Dieses Repository beinhaltet HTML- und Javascript Code zur einer NotizenWebApp auf Basis von Web Storage. Zudem sind Mocha/Chai Tests im Browser enthalten. https://meinenotizen.netlify.app/
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.

README.md 11KB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. # faye-websocket [![Build status](https://secure.travis-ci.org/faye/faye-websocket-node.svg)](http://travis-ci.org/faye/faye-websocket-node)
  2. This is a general-purpose WebSocket implementation extracted from the
  3. [Faye](http://faye.jcoglan.com) project. It provides classes for easily building
  4. WebSocket servers and clients in Node. It does not provide a server itself, but
  5. rather makes it easy to handle WebSocket connections within an existing
  6. [Node](https://nodejs.org/) application. It does not provide any abstraction
  7. other than the standard [WebSocket
  8. API](https://html.spec.whatwg.org/multipage/comms.html#network).
  9. It also provides an abstraction for handling
  10. [EventSource](https://html.spec.whatwg.org/multipage/comms.html#server-sent-events)
  11. connections, which are one-way connections that allow the server to push data to
  12. the client. They are based on streaming HTTP responses and can be easier to access
  13. via proxies than WebSockets.
  14. ## Installation
  15. ```
  16. $ npm install faye-websocket
  17. ```
  18. ## Handling WebSocket connections in Node
  19. You can handle WebSockets on the server side by listening for HTTP Upgrade
  20. requests, and creating a new socket for the request. This socket object exposes
  21. the usual WebSocket methods for receiving and sending messages. For example this
  22. is how you'd implement an echo server:
  23. ```js
  24. var WebSocket = require('faye-websocket'),
  25. http = require('http');
  26. var server = http.createServer();
  27. server.on('upgrade', function(request, socket, body) {
  28. if (WebSocket.isWebSocket(request)) {
  29. var ws = new WebSocket(request, socket, body);
  30. ws.on('message', function(event) {
  31. ws.send(event.data);
  32. });
  33. ws.on('close', function(event) {
  34. console.log('close', event.code, event.reason);
  35. ws = null;
  36. });
  37. }
  38. });
  39. server.listen(8000);
  40. ```
  41. `WebSocket` objects are also duplex streams, so you could replace the
  42. `ws.on('message', ...)` line with:
  43. ```js
  44. ws.pipe(ws);
  45. ```
  46. Note that under certain circumstances (notably a draft-76 client connecting
  47. through an HTTP proxy), the WebSocket handshake will not be complete after you
  48. call `new WebSocket()` because the server will not have received the entire
  49. handshake from the client yet. In this case, calls to `ws.send()` will buffer
  50. the message in memory until the handshake is complete, at which point any
  51. buffered messages will be sent to the client.
  52. If you need to detect when the WebSocket handshake is complete, you can use the
  53. `onopen` event.
  54. If the connection's protocol version supports it, you can call `ws.ping()` to
  55. send a ping message and wait for the client's response. This method takes a
  56. message string, and an optional callback that fires when a matching pong message
  57. is received. It returns `true` if and only if a ping message was sent. If the
  58. client does not support ping/pong, this method sends no data and returns
  59. `false`.
  60. ```js
  61. ws.ping('Mic check, one, two', function() {
  62. // fires when pong is received
  63. });
  64. ```
  65. ## Using the WebSocket client
  66. The client supports both the plain-text `ws` protocol and the encrypted `wss`
  67. protocol, and has exactly the same interface as a socket you would use in a web
  68. browser. On the wire it identifies itself as `hybi-13`.
  69. ```js
  70. var WebSocket = require('faye-websocket'),
  71. ws = new WebSocket.Client('ws://www.example.com/');
  72. ws.on('open', function(event) {
  73. console.log('open');
  74. ws.send('Hello, world!');
  75. });
  76. ws.on('message', function(event) {
  77. console.log('message', event.data);
  78. });
  79. ws.on('close', function(event) {
  80. console.log('close', event.code, event.reason);
  81. ws = null;
  82. });
  83. ```
  84. The WebSocket client also lets you inspect the status and headers of the
  85. handshake response via its `statusCode` and `headers` properties.
  86. To connect via a proxy, set the `proxy` option to the HTTP origin of the proxy,
  87. including any authorization information, custom headers and TLS config you
  88. require. Only the `origin` setting is required.
  89. ```js
  90. var ws = new WebSocket.Client('ws://www.example.com/', [], {
  91. proxy: {
  92. origin: 'http://username:password@proxy.example.com',
  93. headers: {'User-Agent': 'node'},
  94. tls: {cert: fs.readFileSync('client.crt')}
  95. }
  96. });
  97. ```
  98. The `tls` value is an object that will be passed to
  99. [`tls.connect()`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
  100. ## Subprotocol negotiation
  101. The WebSocket protocol allows peers to select and identify the application
  102. protocol to use over the connection. On the client side, you can set which
  103. protocols the client accepts by passing a list of protocol names when you
  104. construct the socket:
  105. ```js
  106. var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']);
  107. ```
  108. On the server side, you can likewise pass in the list of protocols the server
  109. supports after the other constructor arguments:
  110. ```js
  111. var ws = new WebSocket(request, socket, body, ['irc', 'amqp']);
  112. ```
  113. If the client and server agree on a protocol, both the client- and server-side
  114. socket objects expose the selected protocol through the `ws.protocol` property.
  115. ## Protocol extensions
  116. faye-websocket is based on the
  117. [websocket-extensions](https://github.com/faye/websocket-extensions-node)
  118. framework that allows extensions to be negotiated via the
  119. `Sec-WebSocket-Extensions` header. To add extensions to a connection, pass an
  120. array of extensions to the `:extensions` option. For example, to add
  121. [permessage-deflate](https://github.com/faye/permessage-deflate-node):
  122. ```js
  123. var deflate = require('permessage-deflate');
  124. var ws = new WebSocket(request, socket, body, [], {extensions: [deflate]});
  125. ```
  126. ## Initialization options
  127. Both the server- and client-side classes allow an options object to be passed in
  128. at initialization time, for example:
  129. ```js
  130. var ws = new WebSocket(request, socket, body, protocols, options);
  131. var ws = new WebSocket.Client(url, protocols, options);
  132. ```
  133. `protocols` is an array of subprotocols as described above, or `null`.
  134. `options` is an optional object containing any of these fields:
  135. - `extensions` - an array of
  136. [websocket-extensions](https://github.com/faye/websocket-extensions-node)
  137. compatible extensions, as described above
  138. - `headers` - an object containing key-value pairs representing HTTP headers to
  139. be sent during the handshake process
  140. - `maxLength` - the maximum allowed size of incoming message frames, in bytes.
  141. The default value is `2^26 - 1`, or 1 byte short of 64 MiB.
  142. - `ping` - an integer that sets how often the WebSocket should send ping frames,
  143. measured in seconds
  144. The client accepts some additional options:
  145. - `proxy` - settings for a proxy as described above
  146. - `net` - an object containing settings for the origin server that will be
  147. passed to
  148. [`net.connect()`](https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener)
  149. - `tls` - an object containing TLS settings for the origin server, this will be
  150. passed to
  151. [`tls.connect()`](https://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. - **`on('open', function(event) {})`** fires when the socket connection is
  156. established. Event has no attributes.
  157. - **`on('message', function(event) {})`** fires when the socket receives a
  158. message. Event has one attribute, **`data`**, which is either a `String` (for
  159. text frames) or a `Buffer` (for binary frames).
  160. - **`on('error', function(event) {})`** fires when there is a protocol error due
  161. to bad data sent by the other peer. This event is purely informational, you do
  162. not need to implement error recover.
  163. - **`on('close', function(event) {})`** fires when either the client or the
  164. server closes the connection. Event has two optional attributes, **`code`**
  165. and **`reason`**, that expose the status code and message sent by the peer
  166. that closed the connection.
  167. - **`send(message)`** accepts either a `String` or a `Buffer` and sends a text
  168. or binary message over the connection to the other peer.
  169. - **`ping(message, function() {})`** sends a ping frame with an optional message
  170. and fires the callback when a matching pong is received.
  171. - **`close(code, reason)`** closes the connection, sending the given status code
  172. and reason text, both of which are optional.
  173. - **`version`** is a string containing the version of the `WebSocket` protocol
  174. the connection is using.
  175. - **`protocol`** 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. - **`url`** is a string containing the URL the client used to create the
  213. EventSource.
  214. - **`lastEventId`** 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. - **`headers`** is an object containing custom headers to be set on the
  220. EventSource response.
  221. - **`retry`** is a number that tells the client how long (in seconds) it should
  222. wait after a dropped connection before attempting to reconnect.
  223. - **`ping`** 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.