npm i mqtt
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script><script>// Initialize a global mqtt variableconsole.log(mqtt)</script>
npm i mqtt -gmqtt helpMQTT.js command line interface, available commands are:* publish publish a message to the broker* subscribe subscribe for updates from the broker* version the current MQTT.js version* help help about commandsLaunch 'mqtt help [command]' to know more about the commands.
// const mqtt = require('mqtt')import mqtt from 'mqtt'// Connection optionsconst options = {clean: true, // true: clear session, false: retain sessionconnectTimeout: 4000, // timeout period// Certification InformationclientId: '<your-client-id>',username: '<your-username>',password: '<your-password>',}// concatenated string, specifies the use of connection method via protocol// ws unencrypted WebSocket connection// wss encrypted WebSocket connection// mqtt unencrypted TCP connection// mqtts encrypted TCP connection// wxs WeChat mini program connection// alis Alipay Mini Program connectionconst connectUrl = 'wss://mqtt-xxx.mqtt.tencenttdmq.com:8084/mqtt'const client = mqtt.connect(connectUrl, options)client.on('reconnect', (error) => {console.log('Reconnecting:', error)})client.on('error', (error) => {console.log('Connection failure:', error)})client.on('message', (topic, message) => {console.log('received message:', topic, message.toString())})
Parameter | Description |
topic | Copy the MQTT level 1 Topic from the Topic Prefix page on the cluster detail page in the console. |
connectUrl | The broker connection address can be copied from the Basic infomation > Access information module on the console target cluster. The location is shown below. Format: mqtt-xxx-gz.mqtt.qcloud.tencenttdmq.com:1883. |
clientId | Client ID is obtained from the Client Management page on the cluster details page in the console. |
username | Connection Username can be copied from the Authentication Management page on the cluster details page in the console. |
password | The password matching the Connection Username can be copied from the Authentication Management page on the cluster details page in the console. |
Feedback