source: trip-planner-front/node_modules/engine.io/README.md

Last change on this file was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago

primeNG components

  • Property mode set to 100644
File size: 21.5 KB
RevLine 
[6a3a178]1
2# Engine.IO: the realtime engine
3
[e29cc2e]4[![Build Status](https://github.com/socketio/engine.io/workflows/CI/badge.svg?branch=master)](https://github.com/socketio/engine.io/actions)
[6a3a178]5[![NPM version](https://badge.fury.io/js/engine.io.svg)](http://badge.fury.io/js/engine.io)
6
7`Engine.IO` is the implementation of transport-based
8cross-browser/cross-device bi-directional communication layer for
9[Socket.IO](http://github.com/socketio/socket.io).
10
11## How to use
12
13### Server
14
15#### (A) Listening on a port
16
17```js
18const engine = require('engine.io');
19const server = engine.listen(80);
20
21server.on('connection', socket => {
22 socket.send('utf 8 string');
23 socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
24});
25```
26
27#### (B) Intercepting requests for a http.Server
28
29```js
30const engine = require('engine.io');
31const http = require('http').createServer().listen(3000);
32const server = engine.attach(http);
33
34server.on('connection', socket => {
35 socket.on('message', data => { });
36 socket.on('close', () => { });
37});
38```
39
40#### (C) Passing in requests
41
42```js
43const engine = require('engine.io');
44const server = new engine.Server();
45
46server.on('connection', socket => {
47 socket.send('hi');
48});
49
50// …
51httpServer.on('upgrade', (req, socket, head) => {
52 server.handleUpgrade(req, socket, head);
53});
54
55httpServer.on('request', (req, res) => {
56 server.handleRequest(req, res);
57});
58```
59
60### Client
61
62```html
63<script src="/path/to/engine.io.js"></script>
64<script>
65 const socket = new eio.Socket('ws://localhost/');
66 socket.on('open', () => {
67 socket.on('message', data => {});
68 socket.on('close', () => {});
69 });
70</script>
71```
72
73For more information on the client refer to the
74[engine-client](http://github.com/socketio/engine.io-client) repository.
75
76## What features does it have?
77
78- **Maximum reliability**. Connections are established even in the presence of:
79 - proxies and load balancers.
80 - personal firewall and antivirus software.
81 - for more information refer to **Goals** and **Architecture** sections
82- **Minimal client size** aided by:
83 - lazy loading of flash transports.
84 - lack of redundant transports.
85- **Scalable**
86 - load balancer friendly
87- **Future proof**
88- **100% Node.JS core style**
89 - No API sugar (left for higher level projects)
90 - Written in readable vanilla JavaScript
91
92## API
93
94### Server
95
96<hr><br>
97
98#### Top-level
99
100These are exposed by `require('engine.io')`:
101
102##### Events
103
104- `flush`
105 - Called when a socket buffer is being flushed.
106 - **Arguments**
107 - `Socket`: socket being flushed
108 - `Array`: write buffer
109- `drain`
110 - Called when a socket buffer is drained
111 - **Arguments**
112 - `Socket`: socket being flushed
113
114##### Properties
115
116- `protocol` _(Number)_: protocol revision number
117- `Server`: Server class constructor
118- `Socket`: Socket class constructor
119- `Transport` _(Function)_: transport constructor
120- `transports` _(Object)_: map of available transports
121
122##### Methods
123
124- `()`
125 - Returns a new `Server` instance. If the first argument is an `http.Server` then the
126 new `Server` instance will be attached to it. Otherwise, the arguments are passed
127 directly to the `Server` constructor.
128 - **Parameters**
129 - `http.Server`: optional, server to attach to.
130 - `Object`: optional, options object (see `Server#constructor` api docs below)
131
132 The following are identical ways to instantiate a server and then attach it.
133
134```js
135const httpServer; // previously created with `http.createServer();` from node.js api.
136
137// create a server first, and then attach
138const eioServer = require('engine.io').Server();
139eioServer.attach(httpServer);
140
141// or call the module as a function to get `Server`
142const eioServer = require('engine.io')();
143eioServer.attach(httpServer);
144
145// immediately attach
146const eioServer = require('engine.io')(httpServer);
147
148// with custom options
149const eioServer = require('engine.io')(httpServer, {
150 maxHttpBufferSize: 1e3
151});
152```
153
154- `listen`
155 - Creates an `http.Server` which listens on the given port and attaches WS
156 to it. It returns `501 Not Implemented` for regular http requests.
157 - **Parameters**
158 - `Number`: port to listen on.
159 - `Object`: optional, options object
160 - `Function`: callback for `listen`.
161 - **Options**
162 - All options from `Server.attach` method, documented below.
163 - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
164 - **Returns** `Server`
165
166```js
167const engine = require('engine.io');
168const server = engine.listen(3000, {
169 pingTimeout: 2000,
170 pingInterval: 10000
171});
172
173server.on('connection', /* ... */);
174```
175
176- `attach`
177 - Captures `upgrade` requests for a `http.Server`. In other words, makes
178 a regular http.Server WebSocket-compatible.
179 - **Parameters**
180 - `http.Server`: server to attach to.
181 - `Object`: optional, options object
182 - **Options**
183 - All options from `Server.attach` method, documented below.
184 - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
185 - **Returns** `Server` a new Server instance.
186
187```js
188const engine = require('engine.io');
189const httpServer = require('http').createServer().listen(3000);
190const server = engine.attach(httpServer, {
[e29cc2e]191 wsEngine: require('eiows').Server // requires having eiows as dependency
[6a3a178]192});
193
194server.on('connection', /* ... */);
195```
196
197#### Server
198
199The main server/manager. _Inherits from EventEmitter_.
200
201##### Events
202
203- `connection`
204 - Fired when a new connection is established.
205 - **Arguments**
206 - `Socket`: a Socket object
207
[e29cc2e]208- `initial_headers`
209 - Fired on the first request of the connection, before writing the response headers
210 - **Arguments**
211 - `headers` (`Object`): a hash of headers
212 - `req` (`http.IncomingMessage`): the request
213
214- `headers`
215 - Fired on the all requests of the connection, before writing the response headers
216 - **Arguments**
217 - `headers` (`Object`): a hash of headers
218 - `req` (`http.IncomingMessage`): the request
219
220- `connection_error`
221 - Fired when an error occurs when establishing the connection.
222 - **Arguments**
223 - `error`: an object with following properties:
224 - `req` (`http.IncomingMessage`): the request that was dropped
225 - `code` (`Number`): one of `Server.errors`
226 - `message` (`string`): one of `Server.errorMessages`
227 - `context` (`Object`): extra info about the error
228
229| Code | Message |
230| ---- | ------- |
231| 0 | "Transport unknown"
232| 1 | "Session ID unknown"
233| 2 | "Bad handshake method"
234| 3 | "Bad request"
235| 4 | "Forbidden"
236| 5 | "Unsupported protocol version"
237
238
[6a3a178]239##### Properties
240
241**Important**: if you plan to use Engine.IO in a scalable way, please
242keep in mind the properties below will only reflect the clients connected
243to a single process.
244
245- `clients` _(Object)_: hash of connected clients by id.
246- `clientsCount` _(Number)_: number of connected clients.
247
248##### Methods
249
250- **constructor**
251 - Initializes the server
252 - **Parameters**
253 - `Object`: optional, options object
254 - **Options**
255 - `pingTimeout` (`Number`): how many ms without a pong packet to
[e29cc2e]256 consider the connection closed (`20000`)
[6a3a178]257 - `pingInterval` (`Number`): how many ms before sending a new ping
258 packet (`25000`)
259 - `upgradeTimeout` (`Number`): how many ms before an uncompleted transport upgrade is cancelled (`10000`)
260 - `maxHttpBufferSize` (`Number`): how many bytes or characters a message
261 can be, before closing the session (to avoid DoS). Default
262 value is `1E6`.
263 - `allowRequest` (`Function`): A function that receives a given handshake
264 or upgrade request as its first parameter, and can decide whether to
265 continue or not. The second argument is a function that needs to be
266 called with the decided information: `fn(err, success)`, where
267 `success` is a boolean value where false means that the request is
268 rejected, and err is an error code.
269 - `transports` (`<Array> String`): transports to allow connections
270 to (`['polling', 'websocket']`)
271 - `allowUpgrades` (`Boolean`): whether to allow transport upgrades
272 (`true`)
273 - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension
274 (see [ws module](https://github.com/einaros/ws) api docs). Set to `true` to enable. (defaults to `false`)
275 - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
276 - `httpCompression` (`Object|Boolean`): parameters of the http compression for the polling transports
277 (see [zlib](http://nodejs.org/api/zlib.html#zlib_options) api docs). Set to `false` to disable. (`true`)
278 - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
279 - `cookie` (`Object|Boolean`): configuration of the cookie that
280 contains the client sid to send as part of handshake response
281 headers. This cookie might be used for sticky-session. Defaults to not sending any cookie (`false`).
282 See [here](https://github.com/jshttp/cookie#options-1) for all supported options.
[e29cc2e]283 - `wsEngine` (`Function`): what WebSocket server implementation to use. Specified module must conform to the `ws` interface (see [ws module api docs](https://github.com/websockets/ws/blob/master/doc/ws.md)). Default value is `ws`. An alternative c++ addon is also available by installing `eiows` module.
[6a3a178]284 - `cors` (`Object`): the options that will be forwarded to the cors module. See [there](https://github.com/expressjs/cors#configuration-options) for all available options. Defaults to no CORS allowed.
285 - `initialPacket` (`Object`): an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
286 - `allowEIO3` (`Boolean`): whether to support v3 Engine.IO clients (defaults to `false`)
287- `close`
288 - Closes all clients
289 - **Returns** `Server` for chaining
290- `handleRequest`
291 - Called internally when a `Engine` request is intercepted.
292 - **Parameters**
293 - `http.IncomingMessage`: a node request object
294 - `http.ServerResponse`: a node response object
295 - **Returns** `Server` for chaining
296- `handleUpgrade`
297 - Called internally when a `Engine` ws upgrade is intercepted.
298 - **Parameters** (same as `upgrade` event)
299 - `http.IncomingMessage`: a node request object
300 - `net.Stream`: TCP socket for the request
301 - `Buffer`: legacy tail bytes
302 - **Returns** `Server` for chaining
303- `attach`
304 - Attach this Server instance to an `http.Server`
305 - Captures `upgrade` requests for a `http.Server`. In other words, makes
306 a regular http.Server WebSocket-compatible.
307 - **Parameters**
308 - `http.Server`: server to attach to.
309 - `Object`: optional, options object
310 - **Options**
311 - `path` (`String`): name of the path to capture (`/engine.io`).
312 - `destroyUpgrade` (`Boolean`): destroy unhandled upgrade requests (`true`)
313 - `destroyUpgradeTimeout` (`Number`): milliseconds after which unhandled requests are ended (`1000`)
314- `generateId`
315 - Generate a socket id.
316 - Overwrite this method to generate your custom socket id.
317 - **Parameters**
318 - `http.IncomingMessage`: a node request object
319 - **Returns** A socket id for connected client.
320
321<hr><br>
322
323#### Socket
324
325A representation of a client. _Inherits from EventEmitter_.
326
327##### Events
328
329- `close`
330 - Fired when the client is disconnected.
331 - **Arguments**
332 - `String`: reason for closing
333 - `Object`: description object (optional)
334- `message`
335 - Fired when the client sends a message.
336 - **Arguments**
337 - `String` or `Buffer`: Unicode string or Buffer with binary contents
338- `error`
339 - Fired when an error occurs.
340 - **Arguments**
341 - `Error`: error object
342- `flush`
343 - Called when the write buffer is being flushed.
344 - **Arguments**
345 - `Array`: write buffer
346- `drain`
347 - Called when the write buffer is drained
348- `packet`
349 - Called when a socket received a packet (`message`, `ping`)
350 - **Arguments**
351 - `type`: packet type
352 - `data`: packet data (if type is message)
353- `packetCreate`
354 - Called before a socket sends a packet (`message`, `ping`)
355 - **Arguments**
356 - `type`: packet type
357 - `data`: packet data (if type is message)
[e29cc2e]358- `heartbeat`
359 - Called when `ping` or `pong` packed is received (depends of client version)
[6a3a178]360
361##### Properties
362
363- `id` _(String)_: unique identifier
364- `server` _(Server)_: engine parent reference
365- `request` _(http.IncomingMessage)_: request that originated the Socket
366- `upgraded` _(Boolean)_: whether the transport has been upgraded
367- `readyState` _(String)_: opening|open|closing|closed
368- `transport` _(Transport)_: transport reference
369
370##### Methods
371
372- `send`:
373 - Sends a message, performing `message = toString(arguments[0])` unless
374 sending binary data, which is sent as is.
375 - **Parameters**
376 - `String` | `Buffer` | `ArrayBuffer` | `ArrayBufferView`: a string or any object implementing `toString()`, with outgoing data, or a Buffer or ArrayBuffer with binary data. Also any ArrayBufferView can be sent as is.
377 - `Object`: optional, options object
378 - `Function`: optional, a callback executed when the message gets flushed out by the transport
379 - **Options**
380 - `compress` (`Boolean`): whether to compress sending data. This option might be ignored and forced to be `true` when using polling. (`true`)
381 - **Returns** `Socket` for chaining
382- `close`
383 - Disconnects the client
384 - **Returns** `Socket` for chaining
385
386### Client
387
388<hr><br>
389
390Exposed in the `eio` global namespace (in the browser), or by
391`require('engine.io-client')` (in Node.JS).
392
393For the client API refer to the
394[engine-client](http://github.com/learnboost/engine.io-client) repository.
395
396## Debug / logging
397
398Engine.IO is powered by [debug](http://github.com/visionmedia/debug).
399In order to see all the debug output, run your app with the environment variable
400`DEBUG` including the desired scope.
401
402To see the output from all of Engine.IO's debugging scopes you can use:
403
404```
405DEBUG=engine* node myapp
406```
407
408## Transports
409
410- `polling`: XHR / JSONP polling transport.
411- `websocket`: WebSocket transport.
412
413## Plugins
414
415- [engine.io-conflation](https://github.com/EugenDueck/engine.io-conflation): Makes **conflation and aggregation** of messages straightforward.
416
417## Support
418
419The support channels for `engine.io` are the same as `socket.io`:
420 - irc.freenode.net **#socket.io**
421 - [Google Groups](http://groups.google.com/group/socket_io)
422 - [Website](http://socket.io)
423
424## Development
425
426To contribute patches, run tests or benchmarks, make sure to clone the
427repository:
428
429```
430git clone git://github.com/LearnBoost/engine.io.git
431```
432
433Then:
434
435```
436cd engine.io
437npm install
438```
439
440## Tests
441
442Tests run with `npm test`. It runs the server tests that are aided by
443the usage of `engine.io-client`.
444
445Make sure `npm install` is run first.
446
447## Goals
448
449The main goal of `Engine` is ensuring the most reliable realtime communication.
450Unlike the previous Socket.IO core, it always establishes a long-polling
451connection first, then tries to upgrade to better transports that are "tested" on
452the side.
453
454During the lifetime of the Socket.IO projects, we've found countless drawbacks
455to relying on `HTML5 WebSocket` or `Flash Socket` as the first connection
456mechanisms.
457
458Both are clearly the _right way_ of establishing a bidirectional communication,
459with HTML5 WebSocket being the way of the future. However, to answer most business
460needs, alternative traditional HTTP 1.1 mechanisms are just as good as delivering
461the same solution.
462
463WebSocket based connections have two fundamental benefits:
464
4651. **Better server performance**
466 - _A: Load balancers_<br>
467 Load balancing a long polling connection poses a serious architectural nightmare
468 since requests can come from any number of open sockets by the user agent, but
469 they all need to be routed to the process and computer that owns the `Engine`
470 connection. This negatively impacts RAM and CPU usage.
471 - _B: Network traffic_<br>
472 WebSocket is designed around the premise that each message frame has to be
473 surrounded by the least amount of data. In HTTP 1.1 transports, each message
474 frame is surrounded by HTTP headers and chunked encoding frames. If you try to
475 send the message _"Hello world"_ with xhr-polling, the message ultimately
476 becomes larger than if you were to send it with WebSocket.
477 - _C: Lightweight parser_<br>
478 As an effect of **B**, the server has to do a lot more work to parse the network
479 data and figure out the message when traditional HTTP requests are used
480 (as in long polling). This means that another advantage of WebSocket is
481 less server CPU usage.
482
4832. **Better user experience**
484
485 Due to the reasons stated in point **1**, the most important effect of being able
486 to establish a WebSocket connection is raw data transfer speed, which translates
487 in _some_ cases in better user experience.
488
489 Applications with heavy realtime interaction (such as games) will benefit greatly,
490 whereas applications like realtime chat (Gmail/Facebook), newsfeeds (Facebook) or
491 timelines (Twitter) will have negligible user experience improvements.
492
493Having said this, attempting to establish a WebSocket connection directly so far has
494proven problematic:
495
4961. **Proxies**<br>
497 Many corporate proxies block WebSocket traffic.
498
4992. **Personal firewall and antivirus software**<br>
500 As a result of our research, we've found that at least 3 personal security
501 applications block WebSocket traffic.
502
5033. **Cloud application platforms**<br>
504 Platforms like Heroku or No.de have had trouble keeping up with the fast-paced
505 nature of the evolution of the WebSocket protocol. Applications therefore end up
506 inevitably using long polling, but the seamless installation experience of
507 Socket.IO we strive for (_"require() it and it just works"_) disappears.
508
509Some of these problems have solutions. In the case of proxies and personal programs,
510however, the solutions many times involve upgrading software. Experience has shown
511that relying on client software upgrades to deliver a business solution is
512fruitless: the very existence of this project has to do with a fragmented panorama
513of user agent distribution, with clients connecting with latest versions of the most
514modern user agents (Chrome, Firefox and Safari), but others with versions as low as
515IE 5.5.
516
517From the user perspective, an unsuccessful WebSocket connection can translate in
518up to at least 10 seconds of waiting for the realtime application to begin
519exchanging data. This **perceptively** hurts user experience.
520
521To summarize, **Engine** focuses on reliability and user experience first, marginal
522potential UX improvements and increased server performance second. `Engine` is the
523result of all the lessons learned with WebSocket in the wild.
524
525## Architecture
526
527The main premise of `Engine`, and the core of its existence, is the ability to
528swap transports on the fly. A connection starts as xhr-polling, but it can
529switch to WebSocket.
530
531The central problem this poses is: how do we switch transports without losing
532messages?
533
534`Engine` only switches from polling to another transport in between polling
535cycles. Since the server closes the connection after a certain timeout when
536there's no activity, and the polling transport implementation buffers messages
537in between connections, this ensures no message loss and optimal performance.
538
539Another benefit of this design is that we workaround almost all the limitations
540of **Flash Socket**, such as slow connection times, increased file size (we can
541safely lazy load it without hurting user experience), etc.
542
543## FAQ
544
545### Can I use engine without Socket.IO ?
546
547Absolutely. Although the recommended framework for building realtime applications
548is Socket.IO, since it provides fundamental features for real-world applications
549such as multiplexing, reconnection support, etc.
550
551`Engine` is to Socket.IO what Connect is to Express. An essential piece for building
552realtime frameworks, but something you _probably_ won't be using for building
553actual applications.
554
555### Does the server serve the client?
556
557No. The main reason is that `Engine` is meant to be bundled with frameworks.
558Socket.IO includes `Engine`, therefore serving two clients is not necessary. If
559you use Socket.IO, including
560
561```html
562<script src="/socket.io/socket.io.js">
563```
564
565has you covered.
566
567### Can I implement `Engine` in other languages?
568
569Absolutely. The [engine.io-protocol](https://github.com/socketio/engine.io-protocol)
570repository contains the most up-to-date description of the specification
571at all times.
572
573## License
574
575(The MIT License)
576
577Copyright (c) 2014 Guillermo Rauch &lt;guillermo@learnboost.com&gt;
578
579Permission is hereby granted, free of charge, to any person obtaining
580a copy of this software and associated documentation files (the
581'Software'), to deal in the Software without restriction, including
582without limitation the rights to use, copy, modify, merge, publish,
583distribute, sublicense, and/or sell copies of the Software, and to
584permit persons to whom the Software is furnished to do so, subject to
585the following conditions:
586
587The above copyright notice and this permission notice shall be
588included in all copies or substantial portions of the Software.
589
590THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
591EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
592MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
593IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
594CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
595TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
596SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note: See TracBrowser for help on using the repository browser.