2 # Engine.IO: the realtime engine
4 [![Build Status](https://github.com/socketio/engine.io/workflows/CI/badge.svg)](https://github.com/socketio/engine.io/actions)
5 [![NPM version](https://badge.fury.io/js/engine.io.svg)](http://badge.fury.io/js/engine.io)
7 `Engine.IO` is the implementation of transport-based
8 cross-browser/cross-device bi-directional communication layer for
9 [Socket.IO](http://github.com/socketio/socket.io).
15 #### (A) Listening on a port
18 var engine = require('engine.io');
19 var server = engine.listen(80);
21 server.on('connection', function(socket){
22 socket.send('utf 8 string');
23 socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
27 #### (B) Intercepting requests for a http.Server
30 var engine = require('engine.io');
31 var http = require('http').createServer().listen(3000);
32 var server = engine.attach(http);
34 server.on('connection', function (socket) {
35 socket.on('message', function(data){ });
36 socket.on('close', function(){ });
40 #### (C) Passing in requests
43 var engine = require('engine.io');
44 var server = new engine.Server();
46 server.on('connection', function(socket){
51 httpServer.on('upgrade', function(req, socket, head){
52 server.handleUpgrade(req, socket, head);
54 httpServer.on('request', function(req, res){
55 server.handleRequest(req, res);
62 <script src="/path/to/engine.io.js"></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(){});
72 For more information on the client refer to the
73 [engine-client](http://github.com/learnboost/engine.io-client) repository.
75 ## What features does it have?
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.
85 - load balancer friendly
87 - **100% Node.JS core style**
88 - No API sugar (left for higher level projects)
89 - Written in readable vanilla JavaScript
99 These are exposed by `require('engine.io')`:
104 - Called when a socket buffer is being flushed.
106 - `Socket`: socket being flushed
107 - `Array`: write buffer
109 - Called when a socket buffer is drained
111 - `Socket`: socket being flushed
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
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.
128 - `http.Server`: optional, server to attach to.
129 - `Object`: optional, options object (see `Server#constructor` api docs below)
131 The following are identical ways to instantiate a server and then attach it.
134 var httpServer; // previously created with `http.createServer();` from node.js api.
136 // create a server first, and then attach
137 var eioServer = require('engine.io').Server();
138 eioServer.attach(httpServer);
140 // or call the module as a function to get `Server`
141 var eioServer = require('engine.io')();
142 eioServer.attach(httpServer);
144 // immediately attach
145 var eioServer = require('engine.io')(httpServer);
147 // with custom options
148 var eioServer = require('engine.io')(httpServer, {
149 maxHttpBufferSize: 1e3
154 - Creates an `http.Server` which listens on the given port and attaches WS
155 to it. It returns `501 Not Implemented` for regular http requests.
157 - `Number`: port to listen on.
158 - `Object`: optional, options object
159 - `Function`: callback for `listen`.
161 - All options from `Server.attach` method, documented below.
162 - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
163 - **Returns** `Server`
166 var engine = require('engine.io');
167 var server = engine.listen(3000, {
172 server.on('connection', /* ... */);
176 - Captures `upgrade` requests for a `http.Server`. In other words, makes
177 a regular http.Server WebSocket-compatible.
179 - `http.Server`: server to attach to.
180 - `Object`: optional, options object
182 - All options from `Server.attach` method, documented below.
183 - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
184 - **Returns** `Server` a new Server instance.
187 var engine = require('engine.io');
188 var httpServer = require('http').createServer().listen(3000);
189 var server = engine.attach(httpServer, {
190 wsEngine: 'uws' // requires having uws as dependency
193 server.on('connection', /* ... */);
198 The main server/manager. _Inherits from EventEmitter_.
203 - Fired when a new connection is established.
205 - `Socket`: a Socket object
209 **Important**: if you plan to use Engine.IO in a scalable way, please
210 keep in mind the properties below will only reflect the clients connected
213 - `clients` _(Object)_: hash of connected clients by id.
214 - `clientsCount` _(Number)_: number of connected clients.
219 - Initializes the server
221 - `Object`: optional, options object
223 - `pingTimeout` (`Number`): how many ms without a pong packet to
224 consider the connection closed (`5000`)
225 - `pingInterval` (`Number`): how many ms before sending a new ping
227 - `upgradeTimeout` (`Number`): how many ms before an uncompleted transport upgrade is cancelled (`10000`)
228 - `maxHttpBufferSize` (`Number`): how many bytes or characters a message
229 can be, before closing the session (to avoid DoS). Default
231 - `allowRequest` (`Function`): A function that receives a given handshake
232 or upgrade request as its first parameter, and can decide whether to
233 continue or not. The second argument is a function that needs to be
234 called with the decided information: `fn(err, success)`, where
235 `success` is a boolean value where false means that the request is
236 rejected, and err is an error code.
237 - `transports` (`<Array> String`): transports to allow connections
238 to (`['polling', 'websocket']`)
239 - `allowUpgrades` (`Boolean`): whether to allow transport upgrades
241 - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension
242 (see [ws module](https://github.com/einaros/ws) api docs). Set to `true` to enable. (`false`)
243 - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
244 - `httpCompression` (`Object|Boolean`): parameters of the http compression for the polling transports
245 (see [zlib](http://nodejs.org/api/zlib.html#zlib_options) api docs). Set to `false` to disable. (`true`)
246 - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
247 - `cookie` (`String|Boolean`): name of the HTTP cookie that
248 contains the client sid to send as part of handshake response
249 headers. Set to `false` to not send one. (`io`)
250 - `cookiePath` (`String|Boolean`): path of the above `cookie`
251 option. If false, no path will be sent, which means browsers will only send the cookie on the engine.io attached path (`/engine.io`).
252 Set false to not save io cookie on all requests. (`/`)
253 - `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`._
254 - `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.
255 - `initialPacket` (`Object`): an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
258 - **Returns** `Server` for chaining
260 - Called internally when a `Engine` request is intercepted.
262 - `http.IncomingMessage`: a node request object
263 - `http.ServerResponse`: a node response object
264 - **Returns** `Server` for chaining
266 - Called internally when a `Engine` ws upgrade is intercepted.
267 - **Parameters** (same as `upgrade` event)
268 - `http.IncomingMessage`: a node request object
269 - `net.Stream`: TCP socket for the request
270 - `Buffer`: legacy tail bytes
271 - **Returns** `Server` for chaining
273 - Attach this Server instance to an `http.Server`
274 - Captures `upgrade` requests for a `http.Server`. In other words, makes
275 a regular http.Server WebSocket-compatible.
277 - `http.Server`: server to attach to.
278 - `Object`: optional, options object
280 - `path` (`String`): name of the path to capture (`/engine.io`).
281 - `destroyUpgrade` (`Boolean`): destroy unhandled upgrade requests (`true`)
282 - `destroyUpgradeTimeout` (`Number`): milliseconds after which unhandled requests are ended (`1000`)
283 - `handlePreflightRequest` (`Boolean|Function`): whether to let engine.io handle the OPTIONS requests. You can also pass a custom function to handle the requests (`true`)
285 - Generate a socket id.
286 - Overwrite this method to generate your custom socket id.
288 - `http.IncomingMessage`: a node request object
289 - **Returns** A socket id for connected client.
295 A representation of a client. _Inherits from EventEmitter_.
300 - Fired when the client is disconnected.
302 - `String`: reason for closing
303 - `Object`: description object (optional)
305 - Fired when the client sends a message.
307 - `String` or `Buffer`: Unicode string or Buffer with binary contents
309 - Fired when an error occurs.
311 - `Error`: error object
313 - Called when the write buffer is being flushed.
315 - `Array`: write buffer
317 - Called when the write buffer is drained
319 - Called when a socket received a packet (`message`, `ping`)
321 - `type`: packet type
322 - `data`: packet data (if type is message)
324 - Called before a socket sends a packet (`message`, `pong`)
326 - `type`: packet type
327 - `data`: packet data (if type is message)
331 - `id` _(String)_: unique identifier
332 - `server` _(Server)_: engine parent reference
333 - `request` _(http.IncomingMessage)_: request that originated the Socket
334 - `upgraded` _(Boolean)_: whether the transport has been upgraded
335 - `readyState` _(String)_: opening|open|closing|closed
336 - `transport` _(Transport)_: transport reference
341 - Sends a message, performing `message = toString(arguments[0])` unless
342 sending binary data, which is sent as is.
344 - `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.
345 - `Object`: optional, options object
346 - `Function`: optional, a callback executed when the message gets flushed out by the transport
348 - `compress` (`Boolean`): whether to compress sending data. This option might be ignored and forced to be `true` when using polling. (`true`)
349 - **Returns** `Socket` for chaining
351 - Disconnects the client
352 - **Returns** `Socket` for chaining
358 Exposed in the `eio` global namespace (in the browser), or by
359 `require('engine.io-client')` (in Node.JS).
361 For the client API refer to the
362 [engine-client](http://github.com/learnboost/engine.io-client) repository.
366 Engine.IO is powered by [debug](http://github.com/visionmedia/debug).
367 In order to see all the debug output, run your app with the environment variable
368 `DEBUG` including the desired scope.
370 To see the output from all of Engine.IO's debugging scopes you can use:
373 DEBUG=engine* node myapp
378 - `polling`: XHR / JSONP polling transport.
379 - `websocket`: WebSocket transport.
383 - [engine.io-conflation](https://github.com/EugenDueck/engine.io-conflation): Makes **conflation and aggregation** of messages straightforward.
387 The support channels for `engine.io` are the same as `socket.io`:
388 - irc.freenode.net **#socket.io**
389 - [Google Groups](http://groups.google.com/group/socket_io)
390 - [Website](http://socket.io)
394 To contribute patches, run tests or benchmarks, make sure to clone the
398 git clone git://github.com/LearnBoost/engine.io.git
410 Tests run with `npm test`. It runs the server tests that are aided by
411 the usage of `engine.io-client`.
413 Make sure `npm install` is run first.
417 The main goal of `Engine` is ensuring the most reliable realtime communication.
418 Unlike the previous Socket.IO core, it always establishes a long-polling
419 connection first, then tries to upgrade to better transports that are "tested" on
422 During the lifetime of the Socket.IO projects, we've found countless drawbacks
423 to relying on `HTML5 WebSocket` or `Flash Socket` as the first connection
426 Both are clearly the _right way_ of establishing a bidirectional communication,
427 with HTML5 WebSocket being the way of the future. However, to answer most business
428 needs, alternative traditional HTTP 1.1 mechanisms are just as good as delivering
431 WebSocket based connections have two fundamental benefits:
433 1. **Better server performance**
434 - _A: Load balancers_<br>
435 Load balancing a long polling connection poses a serious architectural nightmare
436 since requests can come from any number of open sockets by the user agent, but
437 they all need to be routed to the process and computer that owns the `Engine`
438 connection. This negatively impacts RAM and CPU usage.
439 - _B: Network traffic_<br>
440 WebSocket is designed around the premise that each message frame has to be
441 surrounded by the least amount of data. In HTTP 1.1 transports, each message
442 frame is surrounded by HTTP headers and chunked encoding frames. If you try to
443 send the message _"Hello world"_ with xhr-polling, the message ultimately
444 becomes larger than if you were to send it with WebSocket.
445 - _C: Lightweight parser_<br>
446 As an effect of **B**, the server has to do a lot more work to parse the network
447 data and figure out the message when traditional HTTP requests are used
448 (as in long polling). This means that another advantage of WebSocket is
449 less server CPU usage.
451 2. **Better user experience**
453 Due to the reasons stated in point **1**, the most important effect of being able
454 to establish a WebSocket connection is raw data transfer speed, which translates
455 in _some_ cases in better user experience.
457 Applications with heavy realtime interaction (such as games) will benefit greatly,
458 whereas applications like realtime chat (Gmail/Facebook), newsfeeds (Facebook) or
459 timelines (Twitter) will have negligible user experience improvements.
461 Having said this, attempting to establish a WebSocket connection directly so far has
465 Many corporate proxies block WebSocket traffic.
467 2. **Personal firewall and antivirus software**<br>
468 As a result of our research, we've found that at least 3 personal security
469 applications block WebSocket traffic.
471 3. **Cloud application platforms**<br>
472 Platforms like Heroku or No.de have had trouble keeping up with the fast-paced
473 nature of the evolution of the WebSocket protocol. Applications therefore end up
474 inevitably using long polling, but the seamless installation experience of
475 Socket.IO we strive for (_"require() it and it just works"_) disappears.
477 Some of these problems have solutions. In the case of proxies and personal programs,
478 however, the solutions many times involve upgrading software. Experience has shown
479 that relying on client software upgrades to deliver a business solution is
480 fruitless: the very existence of this project has to do with a fragmented panorama
481 of user agent distribution, with clients connecting with latest versions of the most
482 modern user agents (Chrome, Firefox and Safari), but others with versions as low as
485 From the user perspective, an unsuccessful WebSocket connection can translate in
486 up to at least 10 seconds of waiting for the realtime application to begin
487 exchanging data. This **perceptively** hurts user experience.
489 To summarize, **Engine** focuses on reliability and user experience first, marginal
490 potential UX improvements and increased server performance second. `Engine` is the
491 result of all the lessons learned with WebSocket in the wild.
495 The main premise of `Engine`, and the core of its existence, is the ability to
496 swap transports on the fly. A connection starts as xhr-polling, but it can
499 The central problem this poses is: how do we switch transports without losing
502 `Engine` only switches from polling to another transport in between polling
503 cycles. Since the server closes the connection after a certain timeout when
504 there's no activity, and the polling transport implementation buffers messages
505 in between connections, this ensures no message loss and optimal performance.
507 Another benefit of this design is that we workaround almost all the limitations
508 of **Flash Socket**, such as slow connection times, increased file size (we can
509 safely lazy load it without hurting user experience), etc.
513 ### Can I use engine without Socket.IO ?
515 Absolutely. Although the recommended framework for building realtime applications
516 is Socket.IO, since it provides fundamental features for real-world applications
517 such as multiplexing, reconnection support, etc.
519 `Engine` is to Socket.IO what Connect is to Express. An essential piece for building
520 realtime frameworks, but something you _probably_ won't be using for building
523 ### Does the server serve the client?
525 No. The main reason is that `Engine` is meant to be bundled with frameworks.
526 Socket.IO includes `Engine`, therefore serving two clients is not necessary. If
527 you use Socket.IO, including
530 <script src="/socket.io/socket.io.js">
535 ### Can I implement `Engine` in other languages?
537 Absolutely. The [engine.io-protocol](https://github.com/LearnBoost/engine.io-protocol)
538 repository contains the most up to date description of the specification
539 at all times, and the parser implementation in JavaScript.
545 Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
547 Permission is hereby granted, free of charge, to any person obtaining
548 a copy of this software and associated documentation files (the
549 'Software'), to deal in the Software without restriction, including
550 without limitation the rights to use, copy, modify, merge, publish,
551 distribute, sublicense, and/or sell copies of the Software, and to
552 permit persons to whom the Software is furnished to do so, subject to
553 the following conditions:
555 The above copyright notice and this permission notice shall be
556 included in all copies or substantial portions of the Software.
558 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
559 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
560 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
561 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
562 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
563 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
564 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.