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.

517 lines
18 KiB

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