raspberryGPIOhtmlserver/node_modules/engine.io/README.md
node_modules/engine.io/README.mdRaw
1
2# Engine.IO: the realtime engine
3
4[](http://travis-ci.org/Automattic/engine.io)
5[](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/learnboost/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 - `maxHttpBufferSize` (`Number`): how many bytes or characters a message
203 can be when polling, before closing the session (to avoid DoS). Default
204 value is `10E7`.
205 - `allowRequest` (`Function`): A function that receives a given handshake
206 or upgrade request as its first parameter, and can decide whether to
207 continue or not. The second argument is a function that needs to be
208 called with the decided information: `fn(err, success)`, where
209 `success` is a boolean value where false means that the request is
210 rejected, and err is an error code.
211 - `transports` (`<Array> String`): transports to allow connections
212 to (`['polling', 'websocket']`)
213 - `allowUpgrades` (`Boolean`): whether to allow transport upgrades
214 (`true`)
215 - `cookie` (`String|Boolean`): name of the HTTP cookie that
216 contains the client sid to send as part of handshake response
217 headers. Set to `false` to not send one. (`io`)
218- `close`
219 - Closes all clients
220 - **Returns** `Server` for chaining
221- `handleRequest`
222 - Called internally when a `Engine` request is intercepted.
223 - **Parameters**
224 - `http.ServerRequest`: a node request object
225 - `http.ServerResponse`: a node response object
226 - **Returns** `Server` for chaining
227- `handleUpgrade`
228 - Called internally when a `Engine` ws upgrade is intercepted.
229 - **Parameters** (same as `upgrade` event)
230 - `http.ServerRequest`: a node request object
231 - `net.Stream`: TCP socket for the request
232 - `Buffer`: legacy tail bytes
233 - **Returns** `Server` for chaining
234- `attach`
235 - Attach this Server instance to an `http.Server`
236 - Captures `upgrade` requests for a `http.Server`. In other words, makes
237 a regular http.Server WebSocket-compatible.
238 - **Parameters**
239 - `http.Server`: server to attach to.
240 - `Object`: optional, options object
241 - **Options**
242 - `path` (`String`): name of the path to capture (`/engine.io`).
243 - `destroyUpgrade` (`Boolean`): destroy unhandled upgrade requests (`true`)
244 - `destroyUpgradeTimeout` (`Number`): milliseconds after which unhandled requests are ended (`1000`)
245
246<hr><br>
247
248#### Socket
249
250A representation of a client. _Inherits from EventEmitter_.
251
252##### Events
253
254- `close`
255 - Fired when the client is disconnected.
256 - **Arguments**
257 - `String`: reason for closing
258 - `Object`: description object (optional)
259- `message`
260 - Fired when the client sends a message.
261 - **Arguments**
262 - `String` or `Buffer`: Unicode string or Buffer with binary contents
263- `error`
264 - Fired when an error occurs.
265 - **Arguments**
266 - `Error`: error object
267- `flush`
268 - Called when the write buffer is being flushed.
269 - **Arguments**
270 - `Array`: write buffer
271- `drain`
272 - Called when the write buffer is drained
273- `packet`
274 - Called when a socket received a packet (`message`, `ping`)
275 - **Arguments**
276 - `type`: packet type
277 - `data`: packet data (if type is message)
278- `packetCreate`
279 - Called before a socket sends a packet (`message`, `pong`)
280 - **Arguments**
281 - `type`: packet type
282 - `data`: packet data (if type is message)
283
284##### Properties
285
286- `id` _(String)_: unique identifier
287- `server` _(Server)_: engine parent reference
288- `request` _(http.ServerRequest)_: request that originated the Socket
289- `upgraded` _(Boolean)_: whether the transport has been upgraded
290- `readyState` _(String)_: opening|open|closing|closed
291- `transport` _(Transport)_: transport reference
292
293##### Methods
294
295- `send`:
296 - Sends a message, performing `message = toString(arguments[0])` unless
297 sending binary data, which is sent as is.
298 - **Parameters**
299 - `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.
300 - `Function`: optional, a callback executed when the message gets flushed out by the transport
301 - **Returns** `Socket` for chaining
302- `close`
303 - Disconnects the client
304 - **Returns** `Socket` for chaining
305
306### Client
307
308<hr><br>
309
310Exposed in the `eio` global namespace (in the browser), or by
311`require('engine.io-client')` (in Node.JS).
312
313For the client API refer to the
314[engine-client](http://github.com/learnboost/engine.io-client) repository.
315
316## Debug / logging
317
318Engine.IO is powered by [debug](http://github.com/visionmedia/debug).
319In order to see all the debug output, run your app with the environment variable
320`DEBUG` including the desired scope.
321
322To see the output from all of Engine.IO's debugging scopes you can use:
323
324```
325DEBUG=engine* node myapp
326```
327
328## Transports
329
330- `polling`: XHR / JSONP polling transport.
331- `websocket`: WebSocket transport.
332
333## Plugins
334
335- [engine.io-conflation](https://github.com/EugenDueck/engine.io-conflation): Makes **conflation and aggregation** of messages straightforward.
336
337## Support
338
339The support channels for `engine.io` are the same as `socket.io`:
340 - irc.freenode.net **#socket.io**
341 - [Google Groups](http://groups.google.com/group/socket_io)
342 - [Website](http://socket.io)
343
344## Development
345
346To contribute patches, run tests or benchmarks, make sure to clone the
347repository:
348
349```
350git clone git://github.com/LearnBoost/engine.io.git
351```
352
353Then:
354
355```
356cd engine.io
357npm install
358```
359
360## Tests
361
362Tests run with `make test`. It runs the server tests that are aided by
363the usage of `engine.io-client`.
364
365Make sure `npm install` is run first.
366
367## Goals
368
369The main goal of `Engine` is ensuring the most reliable realtime communication.
370Unlike the previous Socket.IO core, it always establishes a long-polling
371connection first, then tries to upgrade to better transports that are "tested" on
372the side.
373
374During the lifetime of the Socket.IO projects, we've found countless drawbacks
375to relying on `HTML5 WebSocket` or `Flash Socket` as the first connection
376mechanisms.
377
378Both are clearly the _right way_ of establishing a bidirectional communication,
379with HTML5 WebSocket being the way of the future. However, to answer most business
380needs, alternative traditional HTTP 1.1 mechanisms are just as good as delivering
381the same solution.
382
383WebSocket based connections have two fundamental benefits:
384
3851. **Better server performance**
386 - _A: Load balancers_<br>
387 Load balancing a long polling connection poses a serious architectural nightmare
388 since requests can come from any number of open sockets by the user agent, but
389 they all need to be routed to the process and computer that owns the `Engine`
390 connection. This negatively impacts RAM and CPU usage.
391 - _B: Network traffic_<br>
392 WebSocket is designed around the premise that each message frame has to be
393 surrounded by the least amount of data. In HTTP 1.1 transports, each message
394 frame is surrounded by HTTP headers and chunked encoding frames. If you try to
395 send the message _"Hello world"_ with xhr-polling, the message ultimately
396 becomes larger than if you were to send it with WebSocket.
397 - _C: Lightweight parser_<br>
398 As an effect of **B**, the server has to do a lot more work to parse the network
399 data and figure out the message when traditional HTTP requests are used
400 (as in long polling). This means that another advantage of WebSocket is
401 less server CPU usage.
402
4032. **Better user experience**
404
405 Due to the reasons stated in point **1**, the most important effect of being able
406 to establish a WebSocket connection is raw data transfer speed, which translates
407 in _some_ cases in better user experience.
408
409 Applications with heavy realtime interaction (such as games) will benefit greatly,
410 whereas applications like realtime chat (Gmail/Facebook), newsfeeds (Facebook) or
411 timelines (Twitter) will have negligible user experience improvements.
412
413Having said this, attempting to establish a WebSocket connection directly so far has
414proven problematic:
415
4161. **Proxies**<br>
417 Many corporate proxies block WebSocket traffic.
418
4192. **Personal firewall and antivirus software**<br>
420 As a result of our research, we've found that at least 3 personal security
421 applications block WebSocket traffic.
422
4233. **Cloud application platforms**<br>
424 Platforms like Heroku or No.de have had trouble keeping up with the fast-paced
425 nature of the evolution of the WebSocket protocol. Applications therefore end up
426 inevitably using long polling, but the seamless installation experience of
427 Socket.IO we strive for (_"require() it and it just works"_) disappears.
428
429Some of these problems have solutions. In the case of proxies and personal programs,
430however, the solutions many times involve upgrading software. Experience has shown
431that relying on client software upgrades to deliver a business solution is
432fruitless: the very existence of this project has to do with a fragmented panorama
433of user agent distribution, with clients connecting with latest versions of the most
434modern user agents (Chrome, Firefox and Safari), but others with versions as low as
435IE 5.5.
436
437From the user perspective, an unsuccessful WebSocket connection can translate in
438up to at least 10 seconds of waiting for the realtime application to begin
439exchanging data. This **perceptively** hurts user experience.
440
441To summarize, **Engine** focuses on reliability and user experience first, marginal
442potential UX improvements and increased server performance second. `Engine` is the
443result of all the lessons learned with WebSocket in the wild.
444
445## Architecture
446
447The main premise of `Engine`, and the core of its existence, is the ability to
448swap transports on the fly. A connection starts as xhr-polling, but it can
449switch to WebSocket.
450
451The central problem this poses is: how do we switch transports without losing
452messages?
453
454`Engine` only switches from polling to another transport in between polling
455cycles. Since the server closes the connection after a certain timeout when
456there's no activity, and the polling transport implementation buffers messages
457in between connections, this ensures no message loss and optimal performance.
458
459Another benefit of this design is that we workaround almost all the limitations
460of **Flash Socket**, such as slow connection times, increased file size (we can
461safely lazy load it without hurting user experience), etc.
462
463## FAQ
464
465### Can I use engine without Socket.IO ?
466
467Absolutely. Although the recommended framework for building realtime applications
468is Socket.IO, since it provides fundamental features for real-world applications
469such as multiplexing, reconnection support, etc.
470
471`Engine` is to Socket.IO what Connect is to Express. An essential piece for building
472realtime frameworks, but something you _probably_ won't be using for building
473actual applications.
474
475### Does the server serve the client?
476
477No. The main reason is that `Engine` is meant to be bundled with frameworks.
478Socket.IO includes `Engine`, therefore serving two clients is not necessary. If
479you use Socket.IO, including
480
481```html
482<script src="/socket.io/socket.io.js">
483```
484
485has you covered.
486
487### Can I implement `Engine` in other languages?
488
489Absolutely. The [engine.io-protocol](https://github.com/LearnBoost/engine.io-protocol)
490repository contains the most up to date description of the specification
491at all times, and the parser implementation in JavaScript.
492
493## License
494
495(The MIT License)
496
497Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
498
499Permission is hereby granted, free of charge, to any person obtaining
500a copy of this software and associated documentation files (the
501'Software'), to deal in the Software without restriction, including
502without limitation the rights to use, copy, modify, merge, publish,
503distribute, sublicense, and/or sell copies of the Software, and to
504permit persons to whom the Software is furnished to do so, subject to
505the following conditions:
506
507The above copyright notice and this permission notice shall be
508included in all copies or substantial portions of the Software.
509
510THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
511EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
512MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
513IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
514CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
515TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
516SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
517