Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // import MQTT.js
  2. import mqtt from 'mqtt'
  3. // <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
  4. // const mqtt = require('mqtt')
  5.  
  6. // WebSocket connect url
  7. const WebSocket_URL = 'ws://localhost:8083/mqtt'
  8.  
  9. // TCP/TLS connect url
  10. const TCP_URL = 'mqtt://localhost:1883'
  11. const TCP_TLS_URL = 'mqtts://localhost:8883'
  12.  
  13.  
  14. const options = {
  15.       connectTimeout: 4000,
  16.  
  17.       // Authentication
  18.       clientId: 'emqx',
  19.       // username: 'emqx',
  20.       // password: 'emqx',
  21.  
  22.       keepalive: 60,
  23.       clean: true,
  24. }
  25.  
  26. const client = mqtt.connect(TCP_URL, options)
  27.  
  28. // after connect
  29. client.on('connect', () => {
  30.   console.log('Connected to', TCP_URL)
  31.  
  32.   client.subscribe('hello', (err) => {
  33.     console.log(err || 'Subscribe Success')
  34.   })
  35.  
  36.   client.publish('hello', 'Hello EMQ X', (err) => {
  37.     console.log(err || 'Publish Success')
  38.   })
  39.  
  40. })
  41.  
  42. // handle message event
  43. client.on('message', (topic, message) => {
  44.   console.log('Received form', topic, ':', message.toString())
  45.  
  46.   // disconnect
  47.   client.end()
  48. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement