js connection mqtt interface

foreword

Recently, the kafka interface was used in the project, and later the mqtt interface was used. Today, I will record how js connects to mqtt.

Mainly use mqtt.jsthis library, using WebSocket connection.

mqtt

MQTT is a client-server based message publish/subscribe transport protocol, built on the TCP/IP protocol.

mqtt installation

install: npm install mqtt -g ;

Quote:import mqtt from 'mqtt';

Use of mqtt

First, create a client and pass in some connection settings;

    // 连接设置
    var options = {
      clean: true,	// 保留会话
      connectTimeout: 4000,	// 超时时间
      reconnectPeriod: 1000,	// 重连时间间隔
      // 认证信息
      clientId,
      username: '',
      password: '',
    }
    var client = mqtt.connect("ws://10.2.xx.xx:8083/mqtt", options);
    

Then, establish a connection and subscribe to the topic;

  //建立连接
  client.on('connect', function () {
    //订阅主题client.subscribe(topic, '订阅主题');
    client.subscribe(topic);
  })

receive messages;

  // 接收消息
  client.on('message', (topic, message) => {
    console.log(message.toString())
  }) 

Finally, send a message to the subject;

  // 发送信息给 topic(主题) client.publish(topic, '这是给topic发送的信息');
  client.publish(topic, '这是给topic发送的信息');

mqtt request

The mqtt request is actually a websocket request in the browser.

First use http to establish a connection, and then upgrade the protocol to ws protocol for communication.

mqtt request image

sample code

var client = mqtt.connect("ws://10.2.xx.xx:8083/mqtt", {
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    client: true,
    connectTimeout: 4000,
    username: 'admin',
    password: 'public',
    keepalive: 60
  })
  //建立连接
  client.on('connect', function () {
    //订阅主题
    client.subscribe('MQTT-EXP-APPLY-TOPIC');
  })
  
  client.on('error', function (err) {
    console.log('连接错误:', err)
    client.end()
  })
  
  client.on('reconnect', (error) => {
    console.log('正在重连:', error)
  })
  
  // 监听接收消息事件
  client.on('message', (topic, message) => {
    console.log(message.toString())
  }) 
  // 发送信息给 topic
  client.publish('MQTT-EXP-APPLY-TOPIC', '这是给topic发送的信息');

epilogue

This is the end of this article, thank you for watching!

If you have any questions, please correct me!

おすすめ

転載: blog.csdn.net/m0_47901007/article/details/128390203