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