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.

537 lines
20 KiB

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