![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
=======
![Github Test Status](https://github.com/mqttjs/MQTT.js/workflows/MQTT.js%20CI/badge.svg) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
in JavaScript for node.js and the browser.
* [Upgrade notes](#notes)
* [Installation](#install)
* [Example](#example)
* [Command Line Tools](#cli)
* [API](#api)
* [Browser](#browser)
* [Weapp](#weapp)
* [About QoS](#qos)
* [TypeScript](#typescript)
* [Contributing](#contributing)
* [License](#license)
MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
[![JavaScript Style
Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
<a name="notes"></a>
## Important notes for existing users
__v4.0.0__ (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to
debug logging, along with some feature additions.
As a __breaking change__, by default a error handler is built into the MQTT.js client, so if any
errors are emitted and the user has not created an event handler on the client for errors, the client will
not break as a result of unhandled errors. Additionally, typical TLS errors like `ECONNREFUSED`, `ECONNRESET` have been
added to a list of TLS errors that will be emitted from the MQTT.js client, and so can be handled as connection errors.
__v3.0.0__ adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability.
__Note:__ MQTT v5 support is experimental as it has not been implemented by brokers yet.
__v2.0.0__ removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
packets. It also removes all the deprecated functionality in v1.0.0,
mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
subscriptions are restored upon reconnection if `clean: true`.
v1.x.x is now in *LTS*, and it will keep being supported as long as
there are v0.8, v0.10 and v0.12 users.
As a __breaking change__, the `encoding` option in the old client is
removed, and now everything is UTF-8 with the exception of the
`password` in the CONNECT message and `payload` in the PUBLISH message,
which are `Buffer`.
Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
so to support old brokers, please read the [client options doc](#client).
__v1.0.0__ improves the overall architecture of the project, which is now
split into three components: MQTT.js keeps the Client,
[mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
includes the protocol parser and generator. The new Client improves
performance by a 30% factor, embeds Websocket support
([MOWS](http://npm.im/mows) is now deprecated), and it has a better
support for QoS 1 and 2. The previous API is still supported but
deprecated, as such, it is not documented in this README.
<a name="install"></a>
## Installation
```sh
npm install mqtt --save
```
<a name="example"></a>
## Example
For the sake of simplicity, let's put the subscriber and the publisher in the same file:
```js
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
```
output:
```
Hello mqtt
```
If you want to run your own MQTT broker, you can use
[Mosquitto](http://mosquitto.org) or
[Aedes-cli](https://github.com/moscajs/aedes-cli), and launch it.
You can also use a test instance: test.mosquitto.org.
If you do not want to install a separate broker, you can try using the
[Aedes](https://github.com/moscajs/aedes).
to use MQTT.js in the browser see the [browserify](#browserify) section
<a name="promises"></a>
## Promise support
If 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.
<a name="cli"></a>
## Command Line Tools
MQTT.js bundles a command to interact with a broker.
In order to have it available on your path, you should install MQTT.js
globally:
```sh
npm install mqtt -g
```
Then, on one terminal
```
mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
```
On another
```
mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
```
See `mqtt help <command>` for the command help.
<a name="debug"></a>
## Debug Logs
MQTT.js uses the [debug](https://www.npmjs.com/package/debug#cmd) package for debugging purposes. To enable debug logs, add the following environment variable on runtime :
```ps
# (example using PowerShell, the VS Code default)
$env:DEBUG='mqttjs*'
```
<a name="reconnecting"></a>
## About Reconnection
An important part of any websocket connection is what to do when a connection
drops off and the client needs to reconnect. MQTT has built-in reconnection
support that can be configured to behave in ways that suit the application.
#### Refresh Authentication Options / Signed Urls with `transformWsUrl` (Websocket Only)
When an mqtt connection drops and needs to reconnect, it's common to require
that any authentication associated with the connection is kept current with
the underlying auth mechanism. For instance some applications may pass an auth
token with connection options on the initial connection, while other cloud
services may require a url be signed with each connection.
By the time the reconnect happens in the application lifecycle, the original
auth data may have expired.
To address this we can use a hook called `transformWsUrl` to manipulate
either of the connection url or the client options at the time of a reconnect.
Example (update clientId & username on each reconnect):
```
const transformWsUrl = (url, options, client) => {
client.options.username = `token=${this.get_current_auth_token()}`;
client.options.clientId = `${this.get_updated_clientId()}`;
return `${this.get_signed_cloud_url(url)`;
}
const connection = await mqtt.connectAsync(<wss url>, {
...,
transformWsUrl: transformUrl,
});
```
Now every time a new WebSocket connection is opened (hopefully not too often),
we will get a fresh signed url or fresh auth token data.
Note: Currently this hook does _not_ support promises, meaning that in order to
use the latest auth token, you must have some outside mechanism running that
handles application-level authentication refreshing so that the websocket
connection can simply grab the latest valid token or signed url.
#### Enabling Reconnection with `reconnectPeriod` option
To ensure that the mqtt client automatically tries to reconnect when the
connection is dropped, you must set the client option `reconnectPeriod` to a
value greater than 0. A value of 0 will disable reconnection and then terminate
the final connection when it drops.
The default value is 1000 ms which means it will try to reconnect 1 second
after losing the connection.
<a name="api"></a>
## API
* <a href="#connect"><code>mqtt.<b>connect()</b></code></a>
* <a href="#client"><code>mqtt.<b>Client()</b></code></a>
* <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a>
* <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a>
* <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a>
* <a href="#end"><code>mqtt.Client#<b>end()<
没有合适的资源?快使用搜索试试~ 我知道了~
MQTT.js:用于Node.js和浏览器的MQTT客户端
共77个文件
js:41个
pem:12个
ts:7个
需积分: 39 12 下载量 58 浏览量
2021-02-03
15:32:24
上传
评论 1
收藏 161KB ZIP 举报
温馨提示
MQTT.js是协议的客户端库,用JavaScript编写,适用于node.js和浏览器。 MQTT.js是一个OPEN开源项目,请参阅“部分以了解这意味着什么。 现有使用者的重要注意事项 v4.0.0 (发布于04/2020)删除了对所有寿命终止节点版本的支持,现在支持节点v12和v14。 它还对调试日志记录进行了改进,并增加了一些功能。 作为一项重大更改,默认情况下,MQTT.js客户端中内置了一个错误处理程序,因此,如果发出任何错误并且用户尚未在客户端上创建错误的事件处理程序,则客户端不会因未处理而中断错误。 另外,已将典型的TLS错误(例如ECONNREFUSED , ECONNRESET添加到将从MQTT.js客户端发出的TLS错误列表中,因此可以将其视为连接错误。 v3.0.0添加了对MQTT 5的支持,对节点v10.x的支持以及许多提高可靠性的修复程序。 注意: MQTT v5支持是试验性的,因为它尚未由代理实现。 V2.0.0消除了节点V0.8,v0.10和v0.12支持,这是3倍于发送数据包快。 它还删除了v1.0.0中所有不推荐使用的功能,主要是mqtt.c
资源详情
资源评论
资源推荐
收起资源包目录
MQTT_js-master.zip (77个子文件)
MQTT.js-master
.github
workflows
syncToDevOps.yml 699B
nodejs.yml 561B
benchmarks
throughputCounter.js 443B
bombing.js 479B
mqtt.js 408B
example.js 252B
.airtaprc.yml 247B
lib
connect
ws.js 6KB
tcp.js 498B
ali.js 3KB
wx.js 3KB
index.js 4KB
tls.js 1KB
validations.js 1KB
store.js 2KB
client.js 42KB
doc
help.txt 302B
subscribe.txt 1KB
publish.txt 1KB
types
lib
client-options.d.ts 4KB
connect
index.d.ts 348B
store.d.ts 842B
client.d.ts 7KB
store-options.d.ts 102B
index.d.ts 544B
examples
ws
client.js 1KB
aedes_server.js 1KB
client
simple-subscribe.js 175B
simple-publish.js 121B
simple-both.js 317B
secure-client.js 588B
wss
client_with_proxy.js 1KB
tls client
crt.ca.cg.pem 2KB
mqttclient.js 1KB
tls-key.pem 887B
tls-cert.pem 757B
CONTRIBUTING.md 1KB
test
websocket_client.js 5KB
server.js 2KB
server_helpers_for_client_tests.js 3KB
mqtt.js 7KB
store.js 215B
helpers
server.js 1KB
tls-key.pem 2KB
public-key.pem 451B
wrong-key.pem 887B
private-key.pem 2KB
private-csr.pem 956B
port_list.js 852B
wrong-csr.pem 603B
public-cert.pem 1KB
server_process.js 208B
wrong-cert.pem 757B
tls-cert.pem 1KB
abstract_store.js 3KB
browser
server.js 3KB
test.js 2KB
client.js 15KB
util.js 279B
mqtt_store.js 217B
secure_client.js 5KB
client_mqtt5.js 16KB
typescript
tsconfig.json 301B
broker-connect-subscribe-and-publish.ts 1KB
abstract_client.js 91KB
mocha.opts 38B
LICENSE.md 1KB
tslint.json 44B
README.md 31KB
MQTT.js.png 100KB
.npmrc 21B
.editorconfig 147B
.gitignore 275B
bin
mqtt.js 733B
sub.js 3KB
pub.js 3KB
package.json 3KB
共 77 条
- 1
斯里兰卡七七
- 粉丝: 28
- 资源: 4733
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0