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.

295 lines
12 KiB

7 years ago
  1. # Engine.IO client
  2. [![Build Status](https://travis-ci.org/socketio/engine.io-client.svg?branch=master)](http://travis-ci.org/socketio/engine.io-client)
  3. [![NPM version](https://badge.fury.io/js/engine.io-client.svg)](http://badge.fury.io/js/engine.io-client)
  4. This is the client for [Engine.IO](http://github.com/socketio/engine.io),
  5. the implementation of transport-based cross-browser/cross-device
  6. bi-directional communication layer for [Socket.IO](http://github.com/socketio/socket.io).
  7. ## How to use
  8. ### Standalone
  9. You can find an `engine.io.js` file in this repository, which is a
  10. standalone build you can use as follows:
  11. ```html
  12. <script src="/path/to/engine.io.js"></script>
  13. <script>
  14. // eio = Socket
  15. var socket = eio('ws://localhost');
  16. socket.on('open', function(){
  17. socket.on('message', function(data){});
  18. socket.on('close', function(){});
  19. });
  20. </script>
  21. ```
  22. ### With browserify
  23. Engine.IO is a commonjs module, which means you can include it by using
  24. `require` on the browser and package using [browserify](http://browserify.org/):
  25. 1. install the client package
  26. ```bash
  27. $ npm install engine.io-client
  28. ```
  29. 1. write your app code
  30. ```js
  31. var socket = require('engine.io-client')('ws://localhost');
  32. socket.on('open', function(){
  33. socket.on('message', function(data){});
  34. socket.on('close', function(){});
  35. });
  36. ```
  37. 1. build your app bundle
  38. ```bash
  39. $ browserify app.js > bundle.js
  40. ```
  41. 1. include on your page
  42. ```html
  43. <script src="/path/to/bundle.js"></script>
  44. ```
  45. ### Sending and receiving binary
  46. ```html
  47. <script src="/path/to/engine.io.js"></script>
  48. <script>
  49. var socket = new eio.Socket('ws://localhost/');
  50. socket.binaryType = 'blob';
  51. socket.on('open', function () {
  52. socket.send(new Int8Array(5));
  53. socket.on('message', function(blob){});
  54. socket.on('close', function(){ });
  55. });
  56. </script>
  57. ```
  58. ### Node.JS
  59. Add `engine.io-client` to your `package.json` and then:
  60. ```js
  61. var socket = require('engine.io-client')('ws://localhost');
  62. socket.on('open', function(){
  63. socket.on('message', function(data){});
  64. socket.on('close', function(){});
  65. });
  66. ```
  67. ### Node.js with certificates
  68. ```js
  69. var opts = {
  70. key: fs.readFileSync('test/fixtures/client.key'),
  71. cert: fs.readFileSync('test/fixtures/client.crt'),
  72. ca: fs.readFileSync('test/fixtures/ca.crt')
  73. };
  74. var socket = require('engine.io-client')('ws://localhost', opts);
  75. socket.on('open', function(){
  76. socket.on('message', function(data){});
  77. socket.on('close', function(){});
  78. });
  79. ```
  80. ### Node.js with extraHeaders
  81. ```js
  82. var opts = {
  83. extraHeaders: {
  84. 'X-Custom-Header-For-My-Project': 'my-secret-access-token',
  85. 'Cookie': 'user_session=NI2JlCKF90aE0sJZD9ZzujtdsUqNYSBYxzlTsvdSUe35ZzdtVRGqYFr0kdGxbfc5gUOkR9RGp20GVKza; path=/; expires=Tue, 07-Apr-2015 18:18:08 GMT; secure; HttpOnly'
  86. }
  87. };
  88. var socket = require('engine.io-client')('ws://localhost', opts);
  89. socket.on('open', function(){
  90. socket.on('message', function(data){});
  91. socket.on('close', function(){});
  92. });
  93. ```
  94. ## Features
  95. - Lightweight
  96. - Runs on browser and node.js seamlessly
  97. - Transports are independent of `Engine`
  98. - Easy to debug
  99. - Easy to unit test
  100. - Runs inside HTML5 WebWorker
  101. - Can send and receive binary data
  102. - Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer
  103. in Node
  104. - When XHR2 or WebSockets are used, binary is emitted directly. Otherwise
  105. binary is encoded into base64 strings, and decoded when binary types are
  106. supported.
  107. - With browsers that don't support ArrayBuffer, an object { base64: true,
  108. data: dataAsBase64String } is emitted on the `message` event.
  109. ## API
  110. ### Socket
  111. The client class. Mixes in [Emitter](http://github.com/component/emitter).
  112. Exposed as `eio` in the browser standalone build.
  113. #### Properties
  114. - `protocol` _(Number)_: protocol revision number
  115. - `binaryType` _(String)_ : can be set to 'arraybuffer' or 'blob' in browsers,
  116. and `buffer` or `arraybuffer` in Node. Blob is only used in browser if it's
  117. supported.
  118. #### Events
  119. - `open`
  120. - Fired upon successful connection.
  121. - `message`
  122. - Fired when data is received from the server.
  123. - **Arguments**
  124. - `String` | `ArrayBuffer`: utf-8 encoded data or ArrayBuffer containing
  125. binary data
  126. - `close`
  127. - Fired upon disconnection. In compliance with the WebSocket API spec, this event may be
  128. fired even if the `open` event does not occur (i.e. due to connection error or `close()`).
  129. - `error`
  130. - Fired when an error occurs.
  131. - `flush`
  132. - Fired upon completing a buffer flush
  133. - `drain`
  134. - Fired after `drain` event of transport if writeBuffer is empty
  135. - `upgradeError`
  136. - Fired if an error occurs with a transport we're trying to upgrade to.
  137. - `upgrade`
  138. - Fired upon upgrade success, after the new transport is set
  139. - `ping`
  140. - Fired upon _flushing_ a ping packet (ie: actual packet write out)
  141. - `pong`
  142. - Fired upon receiving a pong packet.
  143. #### Methods
  144. - **constructor**
  145. - Initializes the client
  146. - **Parameters**
  147. - `String` uri
  148. - `Object`: optional, options object
  149. - **Options**
  150. - `agent` (`http.Agent`): `http.Agent` to use, defaults to `false` (NodeJS only)
  151. - `upgrade` (`Boolean`): defaults to true, whether the client should try
  152. to upgrade the transport from long-polling to something better.
  153. - `forceJSONP` (`Boolean`): forces JSONP for polling transport.
  154. - `jsonp` (`Boolean`): determines whether to use JSONP when
  155. necessary for polling. If disabled (by settings to false) an error will
  156. be emitted (saying "No transports available") if no other transports
  157. are available. If another transport is available for opening a
  158. connection (e.g. WebSocket) that transport
  159. will be used instead.
  160. - `forceBase64` (`Boolean`): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary.
  161. - `enablesXDR` (`Boolean`): enables XDomainRequest for IE8 to avoid loading bar flashing with click sound. default to `false` because XDomainRequest has a flaw of not sending cookie.
  162. - `timestampRequests` (`Boolean`): whether to add the timestamp with each
  163. transport request. Note: polling requests are always stamped unless this
  164. option is explicitly set to `false` (`false`)
  165. - `timestampParam` (`String`): timestamp parameter (`t`)
  166. - `policyPort` (`Number`): port the policy server listens on (`843`)
  167. - `path` (`String`): path to connect to, default is `/engine.io`
  168. - `transports` (`Array`): a list of transports to try (in order).
  169. Defaults to `['polling', 'websocket']`. `Engine`
  170. always attempts to connect directly with the first one, provided the
  171. feature detection test for it passes.
  172. - `rememberUpgrade` (`Boolean`): defaults to false.
  173. If true and if the previous websocket connection to the server succeeded,
  174. the connection attempt will bypass the normal upgrade process and will initially
  175. try websocket. A connection attempt following a transport error will use the
  176. normal upgrade process. It is recommended you turn this on only when using
  177. SSL/TLS connections, or if you know that your network does not block websockets.
  178. - `pfx` (`String`): Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
  179. - `key` (`String`): Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
  180. - `passphrase` (`String`): A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information.
  181. - `cert` (`String`): Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information.
  182. - `ca` (`String`|`Array`): An authority certificate or array of authority certificates to check the remote host against.. Can be used in Node.js client environment to manually specify certificate information.
  183. - `ciphers` (`String`): A string describing the ciphers to use or exclude. Consult the [cipher format list](http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for details on the format. Can be used in Node.js client environment to manually specify certificate information.
  184. - `rejectUnauthorized` (`Boolean`): If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information.
  185. - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension
  186. (see [ws module](https://github.com/einaros/ws) api docs). Set to `false` to disable. (`true`)
  187. - `threshold` (`Number`): data is compressed only if the byte size is above this value. This option is ignored on the browser. (`1024`)
  188. - `extraHeaders` (`Object`): Headers that will be passed for each request to the server (via xhr-polling and via websockets). These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment.
  189. - `onlyBinaryUpgrades` (`Boolean`): whether transport upgrades should be restricted to transports supporting binary data (`false`)
  190. - `requestTimeout` (`Number`): Timeout for xhr-polling requests in milliseconds (`0`)
  191. - `forceNode` (`Boolean`): Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron) (`false`, NodeJS only)
  192. - `localAddress` (`String`): the local IP address to connect to
  193. - `send`
  194. - Sends a message to the server
  195. - **Parameters**
  196. - `String` | `ArrayBuffer` | `ArrayBufferView` | `Blob`: data to send
  197. - `Object`: optional, options object
  198. - `Function`: optional, callback upon `drain`
  199. - **Options**
  200. - `compress` (`Boolean`): whether to compress sending data. This option is ignored and forced to be `true` on the browser. (`true`)
  201. - `close`
  202. - Disconnects the client.
  203. ### Transport
  204. The transport class. Private. _Inherits from EventEmitter_.
  205. #### Events
  206. - `poll`: emitted by polling transports upon starting a new request
  207. - `pollComplete`: emitted by polling transports upon completing a request
  208. - `drain`: emitted by polling transports upon a buffer drain
  209. ## Tests
  210. `engine.io-client` is used to test
  211. [engine](http://github.com/socketio/engine.io). Running the `engine.io`
  212. test suite ensures the client works and vice-versa.
  213. Browser tests are run using [zuul](https://github.com/defunctzombie/zuul). You can
  214. run the tests locally using the following command.
  215. ```
  216. ./node_modules/.bin/zuul --local 8080 -- test/index.js
  217. ```
  218. Additionally, `engine.io-client` has a standalone test suite you can run
  219. with `make test` which will run node.js and browser tests. You must have zuul setup with
  220. a saucelabs account.
  221. ## Support
  222. The support channels for `engine.io-client` are the same as `socket.io`:
  223. - irc.freenode.net **#socket.io**
  224. - [Google Groups](http://groups.google.com/group/socket_io)
  225. - [Website](http://socket.io)
  226. ## Development
  227. To contribute patches, run tests or benchmarks, make sure to clone the
  228. repository:
  229. ```bash
  230. git clone git://github.com/socketio/engine.io-client.git
  231. ```
  232. Then:
  233. ```bash
  234. cd engine.io-client
  235. npm install
  236. ```
  237. See the `Tests` section above for how to run tests before submitting any patches.
  238. ## License
  239. MIT - Copyright (c) 2014 Automattic, Inc.