UNPKG

28.1 kBMarkdownView Raw
1![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
2=======
3
4[![Build Status](https://travis-ci.org/mqttjs/MQTT.js.svg)](https://travis-ci.org/mqttjs/MQTT.js) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
5
6[![NPM](https://nodei.co/npm-dl/mqtt.png)](https://nodei.co/npm/mqtt/) [![NPM](https://nodei.co/npm/mqtt.png)](https://nodei.co/npm/mqtt/)
7
8[![Sauce Test Status](https://saucelabs.com/browser-matrix/mqttjs.svg)](https://saucelabs.com/u/mqttjs)
9
10MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
11in JavaScript for node.js and the browser.
12
13* [Upgrade notes](#notes)
14* [Installation](#install)
15* [Example](#example)
16* [Command Line Tools](#cli)
17* [API](#api)
18* [Browser](#browser)
19* [Weapp](#weapp)
20* [About QoS](#qos)
21* [TypeScript](#typescript)
22* [Contributing](#contributing)
23* [License](#license)
24
25MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
26
27[![JavaScript Style
28Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
29
30
31<a name="notes"></a>
32## Important notes for existing users
33
34v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
35packets. It also removes all the deprecated functionality in v1.0.0,
36mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
37subscriptions are restored upon reconnection if `clean: true`.
38v1.x.x is now in *LTS*, and it will keep being supported as long as
39there are v0.8, v0.10 and v0.12 users.
40
41v1.0.0 improves the overall architecture of the project, which is now
42split into three components: MQTT.js keeps the Client,
43[mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
44Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
45includes the protocol parser and generator. The new Client improves
46performance by a 30% factor, embeds Websocket support
47([MOWS](http://npm.im/mows) is now deprecated), and it has a better
48support for QoS 1 and 2. The previous API is still supported but
49deprecated, as such, it is not documented in this README.
50
51As a __breaking change__, the `encoding` option in the old client is
52removed, and now everything is UTF-8 with the exception of the
53`password` in the CONNECT message and `payload` in the PUBLISH message,
54which are `Buffer`.
55
56Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
57so to support old brokers, please read the [client options doc](#client).
58
59MQTT v5 support is experimental as it has not been implemented by brokers yet.
60
61<a name="install"></a>
62## Installation
63
64```sh
65npm install mqtt --save
66```
67
68<a name="example"></a>
69## Example
70
71For the sake of simplicity, let's put the subscriber and the publisher in the same file:
72
73```js
74var mqtt = require('mqtt')
75var client = mqtt.connect('mqtt://test.mosquitto.org')
76
77client.on('connect', function () {
78 client.subscribe('presence', function (err) {
79 if (!err) {
80 client.publish('presence', 'Hello mqtt')
81 }
82 })
83})
84
85client.on('message', function (topic, message) {
86 // message is Buffer
87 console.log(message.toString())
88 client.end()
89})
90```
91
92output:
93```
94Hello mqtt
95```
96
97If you want to run your own MQTT broker, you can use
98[Mosquitto](http://mosquitto.org) or
99[Mosca](http://mcollina.github.io/mosca/), and launch it.
100You can also use a test instance: test.mosquitto.org and test.mosca.io
101are both public.
102
103If you do not want to install a separate broker, you can try using the
104[mqtt-connection](https://www.npmjs.com/package/mqtt-connection).
105
106to use MQTT.js in the browser see the [browserify](#browserify) section
107
108<a name="promises"></a>
109## Promise support
110
111If you want to use the new [async-await](https://blog.risingstack.com/async-await-node-js-7-nightly/) functionality in JavaScript, or just prefer using Promises instead of callbacks, [async-mqtt](https://github.com/mqttjs/async-mqtt) is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
112
113<a name="cli"></a>
114## Command Line Tools
115
116MQTT.js bundles a command to interact with a broker.
117In order to have it available on your path, you should install MQTT.js
118globally:
119
120```sh
121npm install mqtt -g
122```
123
124Then, on one terminal
125
126```
127mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
128```
129
130On another
131
132```
133mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
134```
135
136See `mqtt help <command>` for the command help.
137
138<a name="api"></a>
139## API
140
141 * <a href="#connect"><code>mqtt.<b>connect()</b></code></a>
142 * <a href="#client"><code>mqtt.<b>Client()</b></code></a>
143 * <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a>
144 * <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a>
145 * <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a>
146 * <a href="#end"><code>mqtt.Client#<b>end()</b></code></a>
147 * <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a>
148 * <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a>
149 * <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a>
150 * <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a>
151 * <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a>
152 * <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a>
153 * <a href="#store"><code>mqtt.<b>Store()</b></code></a>
154 * <a href="#put"><code>mqtt.Store#<b>put()</b></code></a>
155 * <a href="#del"><code>mqtt.Store#<b>del()</b></code></a>
156 * <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a>
157 * <a href="#close"><code>mqtt.Store#<b>close()</b></code></a>
158
159-------------------------------------------------------
160<a name="connect"></a>
161### mqtt.connect([url], options)
162
163Connects to the broker specified by the given url and options and
164returns a [Client](#client).
165
166The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
167'tls', 'ws', 'wss'. The URL can also be an object as returned by
168[`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
169in that case the two objects are merged, i.e. you can pass a single
170object with both the URL and the connect options.
171
172You can also specify a `servers` options with content: `[{ host:
173'localhost', port: 1883 }, ... ]`, in that case that array is iterated
174at every connect.
175
176For all MQTT-related options, see the [Client](#client)
177constructor.
178
179-------------------------------------------------------
180<a name="client"></a>
181### mqtt.Client(streamBuilder, options)
182
183The `Client` class wraps a client connection to an
184MQTT broker over an arbitrary transport method (TCP, TLS,
185WebSocket, ecc).
186
187`Client` automatically handles the following:
188
189* Regular server pings
190* QoS flow
191* Automatic reconnections
192* Start publishing before being connected
193
194The arguments are:
195
196* `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
197the `connect` event. Typically a `net.Socket`.
198* `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
199 * `wsOptions`: is the WebSocket connection options. Default is `{}`.
200 It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
201 * `keepalive`: `60` seconds, set to `0` to disable
202 * `reschedulePings`: reschedule ping messages after sending packets (default `true`)
203 * `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
204 * `protocolId`: `'MQTT'`
205 * `protocolVersion`: `4`
206 * `clean`: `true`, set to false to receive QoS 1 and 2 messages while
207 offline
208 * `reconnectPeriod`: `1000` milliseconds, interval between two
209 reconnections
210 * `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
211 CONNACK is received
212 * `username`: the username required by your broker, if any
213 * `password`: the password required by your broker, if any
214 * `incomingStore`: a [Store](#store) for the incoming packets
215 * `outgoingStore`: a [Store](#store) for the outgoing packets
216 * `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
217 * `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
218 ```js
219 customHandleAcks: function(topic, message, packet, done) {*some logic wit colling done(error, reasonCode)*}
220 ```
221 * `properties`: properties MQTT 5.0.
222 `object` that supports the following properties:
223 * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
224 * `receiveMaximum`: representing the Receive Maximum value `number`,
225 * `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
226 * `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`,
227 * `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
228 * `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
229 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
230 * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
231 * `authenticationData`: Binary Data containing authentication data `binary`
232 * `authPacket`: settings for auth packet `object`
233 * `will`: a message that will sent by the broker automatically when
234 the client disconnect badly. The format is:
235 * `topic`: the topic to publish
236 * `payload`: the message to publish
237 * `qos`: the QoS
238 * `retain`: the retain flag
239 * `properties`: properties of will by MQTT 5.0:
240 * `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
241 * `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
242 * `messageExpiryInterval`: value is the lifetime of the Will Message in seconds and is sent as the Publication Expiry Interval when the Server publishes the Will Message `number`,
243 * `contentType`: describing the content of the Will Message `string`,
244 * `responseTopic`: String which is used as the Topic Name for a response message `string`,
245 * `correlationData`: The Correlation Data is used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
246 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
247 * `transformWsUrl` : optional `(url, options, client) => url` function
248 For ws/wss protocols only. Can be used to implement signing
249 urls which upon reconnect can have become expired.
250 * `resubscribe` : if connection is broken and reconnects,
251 subscribed topics are automatically subscribed again (default `true`)
252
253In case mqtts (mqtt over tls) is required, the `options` object is
254passed through to
255[`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
256If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
257Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
258that is not recommended for production environments.
259
260If you are connecting to a broker that supports only MQTT 3.1 (not
2613.1.1 compliant), you should pass these additional options:
262
263```js
264{
265 protocolId: 'MQIsdp',
266 protocolVersion: 3
267}
268```
269
270This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
271version 1.3 and 1.4 works fine without those.
272
273#### Event `'connect'`
274
275`function (connack) {}`
276
277Emitted on successful (re)connection (i.e. connack rc=0).
278* `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
279for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
280you may rely on stored session and prefer not to send subscribe commands for the client.
281
282#### Event `'reconnect'`
283
284`function () {}`
285
286Emitted when a reconnect starts.
287
288#### Event `'close'`
289
290`function () {}`
291
292Emitted after a disconnection.
293
294#### Event `'disconnect'`
295
296`function (packet) {}`
297
298Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
299
300#### Event `'offline'`
301
302`function () {}`
303
304Emitted when the client goes offline.
305
306#### Event `'error'`
307
308`function (error) {}`
309
310Emitted when the client cannot connect (i.e. connack rc != 0) or when a
311parsing error occurs.
312
313#### Event `'end'`
314
315`function () {}`
316
317Emitted when <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> is called.
318If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
319callback returns.
320
321#### Event `'message'`
322
323`function (topic, message, packet) {}`
324
325Emitted when the client receives a publish packet
326* `topic` topic of the received packet
327* `message` payload of the received packet
328* `packet` received packet, as defined in
329 [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
330
331#### Event `'packetsend'`
332
333`function (packet) {}`
334
335Emitted when the client sends any packet. This includes .published() packets
336as well as packets used by MQTT for managing subscriptions and connections
337* `packet` received packet, as defined in
338 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
339
340#### Event `'packetreceive'`
341
342`function (packet) {}`
343
344Emitted when the client receives any packet. This includes packets from
345subscribed topics as well as packets used by MQTT for managing subscriptions
346and connections
347* `packet` received packet, as defined in
348 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
349
350-------------------------------------------------------
351<a name="publish"></a>
352### mqtt.Client#publish(topic, message, [options], [callback])
353
354Publish a message to a topic
355
356* `topic` is the topic to publish to, `String`
357* `message` is the message to publish, `Buffer` or `String`
358* `options` is the options to publish with, including:
359 * `qos` QoS level, `Number`, default `0`
360 * `retain` retain flag, `Boolean`, default `false`
361 * `dup` mark as duplicate flag, `Boolean`, default `false`
362 * `properties`: MQTT 5.0 properties `object`
363 * `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
364 * `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
365 * `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
366 * `responseTopic`: String which is used as the Topic Name for a response message `string`,
367 * `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
368 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
369 * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
370 * `contentType`: String describing the content of the Application Message `string`
371 * `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`.
372* `callback` - `function (err)`, fired when the QoS handling completes,
373 or at the next tick if QoS 0. An error occurs if client is disconnecting.
374
375-------------------------------------------------------
376<a name="subscribe"></a>
377### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
378
379Subscribe to a topic or topics
380
381* `topic` is a `String` topic to subscribe to or an `Array` of
382 topics to subscribe to. It can also be an object, it has as object
383 keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`.
384 MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
385* `options` is the options to subscribe with, including:
386 * `qos` qos subscription level, default 0
387 * `nl` No Local MQTT 5.0 flag (If the value is true, Application Messages MUST NOT be forwarded to a connection with a ClientID equal to the ClientID of the publishing connection)
388 * `rap` Retain as Published MQTT 5.0 flag (If true, Application Messages forwarded using this subscription keep the RETAIN flag they were published with. If false, Application Messages forwarded using this subscription have the RETAIN flag set to 0.)
389 * `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.)
390 * `properties`: `object`
391 * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
392 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
393* `callback` - `function (err, granted)`
394 callback fired on suback where:
395 * `err` a subscription error or an error that occurs when client is disconnecting
396 * `granted` is an array of `{topic, qos}` where:
397 * `topic` is a subscribed to topic
398 * `qos` is the granted qos level on it
399
400-------------------------------------------------------
401<a name="unsubscribe"></a>
402### mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
403
404Unsubscribe from a topic or topics
405
406* `topic` is a `String` topic or an array of topics to unsubscribe from
407* `options`: options of unsubscribe.
408 * `properties`: `object`
409 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
410* `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
411
412-------------------------------------------------------
413<a name="end"></a>
414### mqtt.Client#end([force], [options], [cb])
415
416Close the client, accepts the following options:
417
418* `force`: passing it to true will close the client right away, without
419 waiting for the in-flight messages to be acked. This parameter is
420 optional.
421* `options`: options of disconnect.
422 * `reasonCode`: Disconnect Reason Code `number`
423 * `properties`: `object`
424 * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
425 * `reasonString`: representing the reason for the disconnect `string`,
426 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
427 * `serverReference`: String which can be used by the Client to identify another Server to use `string`
428* `cb`: will be called when the client is closed. This parameter is
429 optional.
430
431-------------------------------------------------------
432<a name="removeOutgoingMessage"></a>
433### mqtt.Client#removeOutgoingMessage(mid)
434
435Remove a message from the outgoingStore.
436The outgoing callback will be called with Error('Message removed') if the message is removed.
437
438After this function is called, the messageId is released and becomes reusable.
439
440* `mid`: The messageId of the message in the outgoingStore.
441
442-------------------------------------------------------
443<a name="reconnect"></a>
444### mqtt.Client#reconnect()
445
446Connect again using the same options as connect()
447
448-------------------------------------------------------
449<a name="handleMessage"></a>
450### mqtt.Client#handleMessage(packet, callback)
451
452Handle messages with backpressure support, one at a time.
453Override at will, but __always call `callback`__, or the client
454will hang.
455
456-------------------------------------------------------
457<a name="connected"></a>
458### mqtt.Client#connected
459
460Boolean : set to `true` if the client is connected. `false` otherwise.
461
462-------------------------------------------------------
463<a name="getLastMessageId"></a>
464### mqtt.Client#getLastMessageId()
465
466Number : get last message id. This is for sent messages only.
467
468-------------------------------------------------------
469<a name="reconnecting"></a>
470### mqtt.Client#reconnecting
471
472Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
473
474-------------------------------------------------------
475<a name="store"></a>
476### mqtt.Store(options)
477
478In-memory implementation of the message store.
479
480* `options` is the store options:
481 * `clean`: `true`, clean inflight messages when close is called (default `true`)
482
483Other implementations of `mqtt.Store`:
484
485* [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
486 [Level-browserify](http://npm.im/level-browserify) to store the inflight
487 data, making it usable both in Node and the Browser.
488* [mqtt-nedbb-store](https://github.com/behrad/mqtt-nedb-store) which
489 uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
490 data.
491* [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
492 [localForage](http://npm.im/localforage) to store the inflight
493 data, making it usable in the Browser without browserify.
494
495-------------------------------------------------------
496<a name="put"></a>
497### mqtt.Store#put(packet, callback)
498
499Adds a packet to the store, a packet is
500anything that has a `messageId` property.
501The callback is called when the packet has been stored.
502
503-------------------------------------------------------
504<a name="createStream"></a>
505### mqtt.Store#createStream()
506
507Creates a stream with all the packets in the store.
508
509-------------------------------------------------------
510<a name="del"></a>
511### mqtt.Store#del(packet, cb)
512
513Removes a packet from the store, a packet is
514anything that has a `messageId` property.
515The callback is called when the packet has been removed.
516
517-------------------------------------------------------
518<a name="close"></a>
519### mqtt.Store#close(cb)
520
521Closes the Store.
522
523<a name="browser"></a>
524## Browser
525
526<a name="cdn"></a>
527### Via CDN
528
529The MQTT.js bundle is available through http://unpkg.com, specifically
530at https://unpkg.com/mqtt/dist/mqtt.min.js.
531See http://unpkg.com for the full documentation on version ranges.
532
533<a name="weapp"></a>
534## WeChat Mini Program
535Support [WeChat Mini Program](https://mp.weixin.qq.com/). See [Doc](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).
536<a name="example"></a>
537
538## Example(js)
539
540```js
541var mqtt = require('mqtt')
542var client = mqtt.connect('wxs://test.mosquitto.org')
543```
544
545## Example(ts)
546
547```ts
548import { connect } from 'mqtt';
549const client = connect('wxs://test.mosquitto.org');
550```
551
552## Ali Mini Program
553Surport [Ali Mini Program](https://open.alipay.com/channel/miniIndex.htm). See [Doc](https://docs.alipay.com/mini/developer/getting-started).
554<a name="example"></a>
555
556## Example(js)
557
558```js
559var mqtt = require('mqtt')
560var client = mqtt.connect('alis://test.mosquitto.org')
561```
562
563## Example(ts)
564
565```ts
566import { connect } from 'mqtt';
567const client = connect('alis://test.mosquitto.org');
568```
569
570<a name="browserify"></a>
571### Browserify
572
573In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
574
575```javascript
576npm install -g browserify // install browserify
577cd node_modules/mqtt
578npm install . // install dev dependencies
579browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
580```
581
582<a name="webpack"></a>
583### Webpack
584
585Just like browserify, export MQTT.js as library. The exported module would be `var mqtt = xxx` and it will add an object in the global space. You could also export module in other [formats (AMD/CommonJS/others)](http://webpack.github.io/docs/configuration.html#output-librarytarget) by setting **output.libraryTarget** in webpack configuration.
586
587```javascript
588npm install -g webpack // install webpack
589
590cd node_modules/mqtt
591npm install . // install dev dependencies
592webpack mqtt.js ./browserMqtt.js --output-library mqtt
593```
594
595you can then use mqtt.js in the browser with the same api than node's one.
596
597```html
598<html>
599<head>
600 <title>test Ws mqtt.js</title>
601</head>
602<body>
603<script src="./browserMqtt.js"></script>
604<script>
605 var client = mqtt.connect() // you add a ws:// url here
606 client.subscribe("mqtt/demo")
607
608 client.on("message", function (topic, payload) {
609 alert([topic, payload].join(": "))
610 client.end()
611 })
612
613 client.publish("mqtt/demo", "hello world!")
614</script>
615</body>
616</html>
617```
618
619Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets) to setup [Mosca](http://mcollina.github.io/mosca/)).
620
621<a name="signedurls"></a>
622### Signed WebSocket Urls
623
624If you need to sign an url, for example for [AWS IoT](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws),
625then you can pass in a `transformWsUrl` function to the <a href="#connect"><code>mqtt.<b>connect()</b></code></a> options
626This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
627
628```js
629// This module doesn't actually exist, just an example
630var awsIotUrlSigner = require('awsIotUrlSigner')
631mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
632 transformWsUrl: function (url, options, client) {
633 // It's possible to inspect some state on options(pre parsed url components)
634 // and the client (reconnect state etc)
635 return awsIotUrlSigner(url)
636 }
637})
638
639// Now every time a new WebSocket connection is opened (hopefully not that
640// often) we get a freshly signed url
641
642```
643
644<a name="qos"></a>
645## About QoS
646
647Here is how QoS works:
648
649* QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
650* QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it *will* be received, but there can be duplicates.
651* QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
652
653About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
654
655<a name="typescript"></a>
656## Usage with TypeScript
657This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.
658
659### Pre-requisites
660Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
661 * TypeScript >= 2.1
662 * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
663 * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
664 `npm install --save-dev @types/node`
665
666<a name="contributing"></a>
667## Contributing
668
669MQTT.js is an **OPEN Open Source Project**. This means that:
670
671> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
672
673See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
674
675### Contributors
676
677MQTT.js is only possible due to the excellent work of the following contributors:
678
679<table><tbody>
680<tr><th align="left">Adam Rudd</th><td><a href="https://github.com/adamvr">GitHub/adamvr</a></td><td><a href="http://twitter.com/adam_vr">Twitter/@adam_vr</a></td></tr>
681<tr><th align="left">Matteo Collina</th><td><a href="https://github.com/mcollina">GitHub/mcollina</a></td><td><a href="http://twitter.com/matteocollina">Twitter/@matteocollina</a></td></tr>
682<tr><th align="left">Maxime Agor</th><td><a href="https://github.com/4rzael">GitHub/4rzael</a></td><td><a href="http://twitter.com/4rzael">Twitter/@4rzael</a></td></tr>
683<tr><th align="left">Siarhei Buntsevich</th><td><a href="https://github.com/scarry1992">GitHub/scarry1992</a></td></tr>
684</tbody></table>
685
686<a name="license"></a>
687## License
688
689MIT