Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // import MQTT.js
- import mqtt from 'mqtt'
- // <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
- // const mqtt = require('mqtt')
- // WebSocket connect url
- const WebSocket_URL = 'ws://localhost:8083/mqtt'
- // TCP/TLS connect url
- const TCP_URL = 'mqtt://localhost:1883'
- const TCP_TLS_URL = 'mqtts://localhost:8883'
- const options = {
- connectTimeout: 4000,
- // Authentication
- clientId: 'emqx',
- // username: 'emqx',
- // password: 'emqx',
- keepalive: 60,
- clean: true,
- }
- const client = mqtt.connect(TCP_URL, options)
- // after connect
- client.on('connect', () => {
- console.log('Connected to', TCP_URL)
- client.subscribe('hello', (err) => {
- console.log(err || 'Subscribe Success')
- })
- client.publish('hello', 'Hello EMQ X', (err) => {
- console.log(err || 'Publish Success')
- })
- })
- // handle message event
- client.on('message', (topic, message) => {
- console.log('Received form', topic, ':', message.toString())
- // disconnect
- client.end()
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement