Use mqtt to connect in vue

Expansion of mqtt protocol introduction

1. Install dependencies

npm install mqtt --save

2. Introduced in the project

import mqtt from 'mqtt'

3. Use

 var client = mqtt.connect('ws//****:8083', {
    
     // ws这个为连接类型,还有wss 为加密型
        connectTimeout: 40000,
        clientId: '',
        username: 'user',
        password: 'password',
        clean: true
      })

      client.on('connect', (e) => {
    
    
        // console.log("连接成功!!!", e)
        client.subscribe(['subtitle1','subtitle2'], {
    
    qos: 0}, (error) => {
    
     // qos 为通道
          if (!error) {
    
    
             console.log('订阅成功')
          } else {
    
    
            console.log('订阅失败')
          }
        })
      })
      // 接收消息处理
      client.on('message', (topic, res) => {
    
    
        // console.log('收到来自', topic, '的消息', JSON.stringify(res))
        const resData = JSON.parse(res.toString())
        // 处理返回来的数据
        console.log(resData )
      })
      // 关闭
      // client.end()

Guess you like

Origin blog.csdn.net/super__code/article/details/111994731
Recommended