UNPKG

13.2 kBMarkdownView Raw
1
2# Engine.IO client
3
4[![Build Status](https://github.com/socketio/engine.io-client/workflows/CI/badge.svg?branch=main)](https://github.com/socketio/engine.io-client/actions)
5[![NPM version](https://badge.fury.io/js/engine.io-client.svg)](http://badge.fury.io/js/engine.io-client)
6
7This is the client for [Engine.IO](http://github.com/socketio/engine.io),
8the implementation of transport-based cross-browser/cross-device
9bi-directional communication layer for [Socket.IO](http://github.com/socketio/socket.io).
10
11## How to use
12
13### Standalone
14
15You can find an `engine.io.js` file in this repository, which is a
16standalone build you can use as follows:
17
18```html
19<script src="/path/to/engine.io.js"></script>
20<script>
21 // eio = Socket
22 const socket = eio('ws://localhost');
23 socket.on('open', () => {
24 socket.on('message', (data) => {});
25 socket.on('close', () => {});
26 });
27</script>
28```
29
30### With browserify
31
32Engine.IO is a commonjs module, which means you can include it by using
33`require` on the browser and package using [browserify](http://browserify.org/):
34
351. install the client package
36
37 ```bash
38 $ npm install engine.io-client
39 ```
40
411. write your app code
42
43 ```js
44 const { Socket } = require('engine.io-client');
45 const socket = new Socket('ws://localhost');
46 socket.on('open', () => {
47 socket.on('message', (data) => {});
48 socket.on('close', () => {});
49 });
50 ```
51
521. build your app bundle
53
54 ```bash
55 $ browserify app.js > bundle.js
56 ```
57
581. include on your page
59
60 ```html
61 <script src="/path/to/bundle.js"></script>
62 ```
63
64### Sending and receiving binary
65
66```html
67<script src="/path/to/engine.io.js"></script>
68<script>
69 const socket = eio('ws://localhost/');
70 socket.binaryType = 'blob';
71 socket.on('open', () => {
72 socket.send(new Int8Array(5));
73 socket.on('message', (blob) => {});
74 socket.on('close', () => {});
75 });
76</script>
77```
78
79### Node.JS
80
81Add `engine.io-client` to your `package.json` and then:
82
83```js
84const { Socket } = require('engine.io-client');
85const socket = new Socket('ws://localhost');
86socket.on('open', () => {
87 socket.on('message', (data) => {});
88 socket.on('close', () => {});
89});
90```
91
92### Node.js with certificates
93```js
94const opts = {
95 key: fs.readFileSync('test/fixtures/client.key'),
96 cert: fs.readFileSync('test/fixtures/client.crt'),
97 ca: fs.readFileSync('test/fixtures/ca.crt')
98};
99
100const { Socket } = require('engine.io-client');
101const socket = new Socket('ws://localhost', opts);
102socket.on('open', () => {
103 socket.on('message', (data) => {});
104 socket.on('close', () => {});
105});
106```
107
108### Node.js with extraHeaders
109```js
110const opts = {
111 extraHeaders: {
112 'X-Custom-Header-For-My-Project': 'my-secret-access-token',
113 'Cookie': 'user_session=NI2JlCKF90aE0sJZD9ZzujtdsUqNYSBYxzlTsvdSUe35ZzdtVRGqYFr0kdGxbfc5gUOkR9RGp20GVKza; path=/; expires=Tue, 07-Apr-2015 18:18:08 GMT; secure; HttpOnly'
114 }
115};
116
117const { Socket } = require('engine.io-client');
118const socket = new Socket('ws://localhost', opts);
119socket.on('open', () => {
120 socket.on('message', (data) => {});
121 socket.on('close', () => {});
122});
123```
124
125In the browser, the [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object does not support additional headers.
126In case you want to add some headers as part of some authentication mechanism, you can use the `transportOptions` attribute.
127Please note that in this case the headers won't be sent in the WebSocket upgrade request.
128
129```js
130// WILL NOT WORK in the browser
131const socket = new Socket('http://localhost', {
132 extraHeaders: {
133 'X-Custom-Header-For-My-Project': 'will not be sent'
134 }
135});
136// WILL NOT WORK
137const socket = new Socket('http://localhost', {
138 transports: ['websocket'], // polling is disabled
139 transportOptions: {
140 polling: {
141 extraHeaders: {
142 'X-Custom-Header-For-My-Project': 'will not be sent'
143 }
144 }
145 }
146});
147// WILL WORK
148const socket = new Socket('http://localhost', {
149 transports: ['polling', 'websocket'],
150 transportOptions: {
151 polling: {
152 extraHeaders: {
153 'X-Custom-Header-For-My-Project': 'will be used'
154 }
155 }
156 }
157});
158```
159
160## Features
161
162- Lightweight
163- Runs on browser and node.js seamlessly
164- Transports are independent of `Engine`
165 - Easy to debug
166 - Easy to unit test
167- Runs inside HTML5 WebWorker
168- Can send and receive binary data
169 - Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer
170 in Node
171 - When XHR2 or WebSockets are used, binary is emitted directly. Otherwise
172 binary is encoded into base64 strings, and decoded when binary types are
173 supported.
174 - With browsers that don't support ArrayBuffer, an object { base64: true,
175 data: dataAsBase64String } is emitted on the `message` event.
176
177## API
178
179### Socket
180
181The client class. Mixes in [Emitter](http://github.com/component/emitter).
182Exposed as `eio` in the browser standalone build.
183
184#### Properties
185
186- `protocol` _(Number)_: protocol revision number
187- `binaryType` _(String)_ : can be set to 'arraybuffer' or 'blob' in browsers,
188 and `buffer` or `arraybuffer` in Node. Blob is only used in browser if it's
189 supported.
190
191#### Events
192
193- `open`
194 - Fired upon successful connection.
195- `message`
196 - Fired when data is received from the server.
197 - **Arguments**
198 - `String` | `ArrayBuffer`: utf-8 encoded data or ArrayBuffer containing
199 binary data
200- `close`
201 - Fired upon disconnection. In compliance with the WebSocket API spec, this event may be
202 fired even if the `open` event does not occur (i.e. due to connection error or `close()`).
203- `error`
204 - Fired when an error occurs.
205- `flush`
206 - Fired upon completing a buffer flush
207- `drain`
208 - Fired after `drain` event of transport if writeBuffer is empty
209- `upgradeError`
210 - Fired if an error occurs with a transport we're trying to upgrade to.
211- `upgrade`
212 - Fired upon upgrade success, after the new transport is set
213- `ping`
214 - Fired upon receiving a ping packet.
215- `pong`
216 - Fired upon _flushing_ a pong packet (ie: actual packet write out)
217
218#### Methods
219
220- **constructor**
221 - Initializes the client
222 - **Parameters**
223 - `String` uri
224 - `Object`: optional, options object
225 - **Options**
226 - `agent` (`http.Agent`): `http.Agent` to use, defaults to `false` (NodeJS only)
227 - `upgrade` (`Boolean`): defaults to true, whether the client should try
228 to upgrade the transport from long-polling to something better.
229 - `forceBase64` (`Boolean`): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary.
230 - `withCredentials` (`Boolean`): defaults to `false`, whether to include credentials (cookies, authorization headers, TLS client certificates, etc.) with cross-origin XHR polling requests.
231 - `timestampRequests` (`Boolean`): whether to add the timestamp with each
232 transport request. Note: polling requests are always stamped unless this
233 option is explicitly set to `false` (`false`)
234 - `timestampParam` (`String`): timestamp parameter (`t`)
235 - `path` (`String`): path to connect to, default is `/engine.io`
236 - `transports` (`Array`): a list of transports to try (in order).
237 Defaults to `['polling', 'websocket', 'webtransport']`. `Engine`
238 always attempts to connect directly with the first one, provided the
239 feature detection test for it passes.
240 - `transportOptions` (`Object`): hash of options, indexed by transport name, overriding the common options for the given transport
241 - `rememberUpgrade` (`Boolean`): defaults to false.
242 If true and if the previous websocket connection to the server succeeded,
243 the connection attempt will bypass the normal upgrade process and will initially
244 try websocket. A connection attempt following a transport error will use the
245 normal upgrade process. It is recommended you turn this on only when using
246 SSL/TLS connections, or if you know that your network does not block websockets.
247 - `pfx` (`String`|`Buffer`): Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
248 - `key` (`String`): Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information.
249 - `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.
250 - `cert` (`String`): Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information.
251 - `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.
252 - `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.
253 - `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.
254 - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension
255 (see [ws module](https://github.com/einaros/ws) api docs). Set to `false` to disable. (`true`)
256 - `threshold` (`Number`): data is compressed only if the byte size is above this value. This option is ignored on the browser. (`1024`)
257 - `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.
258 - `localAddress` (`String`): the local IP address to connect to
259 - `autoUnref` (`Boolean`): whether the transport should be `unref`'d upon creation. This calls `unref` on the underlying timers and sockets so that the program is allowed to exit if they are the only timers/sockets in the event system (Node.js only)
260 - `useNativeTimers` (`Boolean`): Whether to always use the native timeouts. This allows the client to reconnect when the native timeout functions are overridden, such as when mock clocks are installed with [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
261 - **Polling-only options**
262 - `requestTimeout` (`Number`): Timeout for xhr-polling requests in milliseconds (`0`)
263 - **Websocket-only options**
264 - `protocols` (`Array`): a list of subprotocols (see [MDN reference](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Subprotocols))
265 - `closeOnBeforeunload` (`Boolean`): whether to silently close the connection when the [`beforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) event is emitted in the browser (defaults to `false`)
266- `send`
267 - Sends a message to the server
268 - **Parameters**
269 - `String` | `ArrayBuffer` | `ArrayBufferView` | `Blob`: data to send
270 - `Object`: optional, options object
271 - `Function`: optional, callback upon `drain`
272 - **Options**
273 - `compress` (`Boolean`): whether to compress sending data. This option is ignored and forced to be `true` on the browser. (`true`)
274- `close`
275 - Disconnects the client.
276
277### Transport
278
279The transport class. Private. _Inherits from EventEmitter_.
280
281#### Events
282
283- `poll`: emitted by polling transports upon starting a new request
284- `pollComplete`: emitted by polling transports upon completing a request
285- `drain`: emitted by polling transports upon a buffer drain
286
287## Tests
288
289`engine.io-client` is used to test
290[engine](http://github.com/socketio/engine.io). Running the `engine.io`
291test suite ensures the client works and vice-versa.
292
293Browser tests are run using [zuul](https://github.com/defunctzombie/zuul). You can
294run the tests locally using the following command.
295
296```
297./node_modules/.bin/zuul --local 8080 -- test/index.js
298```
299
300Additionally, `engine.io-client` has a standalone test suite you can run
301with `make test` which will run node.js and browser tests. You must have zuul setup with
302a saucelabs account.
303
304## Support
305
306The support channels for `engine.io-client` are the same as `socket.io`:
307 - irc.freenode.net **#socket.io**
308 - [Google Groups](http://groups.google.com/group/socket_io)
309 - [Website](http://socket.io)
310
311## Development
312
313To contribute patches, run tests or benchmarks, make sure to clone the
314repository:
315
316```bash
317git clone git://github.com/socketio/engine.io-client.git
318```
319
320Then:
321
322```bash
323cd engine.io-client
324npm install
325```
326
327See the `Tests` section above for how to run tests before submitting any patches.
328
329## License
330
331MIT - Copyright (c) 2014 Automattic, Inc.