How to communicate with MQTT using Go

Introduction

This article describes how to use the Go programming language to communicate with MQTT (Message Queuing Telemetry Transport). MQTT is a lightweight message transmission protocol that is widely used in IoT and real-time communication scenarios. Through the guidance of this article, you will learn how to use the Go language to create an MQTT client to publish and subscribe to messages.

Preparation

Before you begin, make sure you have completed the following preparations:

  • Install the development environment for the Go programming language
  • Understand the basic concepts and working principles of the MQTT protocol
  • Choose an MQTT server or broker as a message relay, such as Eclipse Mosquitto

Install the MQTT Go library

The Go community provides many excellent MQTT client libraries, the more commonly used of which is github.com/eclipse/paho.mqtt.golang. You can install the library using Go's package management tools:

go get github.com/eclipse/paho.mqtt.golang

Create MQTT client

Next, we will create an MQTT client using Go and connect to the MQTT server. Below is a sample code

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

func main() {
    
    
	// 创建 MQTT 客户端配置
	opts := MQTT.NewClientOptions()
	opts.AddBroker("tcp://localhost:1883")
	opts.SetClientID("go-mqtt-client")

	// 创建 MQTT 客户端实例
	client := MQTT.NewClient(opts)

	// 连接到 MQTT 服务器
	if token := client.Connect(); token.Wait() && token.Error() != nil {
    
    
		log.Fatal(token.Error())
	}

	// 在连接成功后进行订阅和发布操作
	go func() {
    
    
		// 订阅主题
		if token := client.Subscribe("my/topic", 0, nil); token.Wait() && token.Error() != nil {
    
    
			log.Fatal(token.Error())
		}

		// 发布消息
		for i := 0; i < 5; i++ {
    
    
			text := fmt.Sprintf("Message %d", i)
			token := client.Publish("my/topic", 0, false, text)
			token.Wait()
			fmt.Println("Published:", text)
			time.Sleep(time.Second)
		}
	}()

	// 等待退出信号
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	// 断开与 MQTT 服务器的连接
	client.Disconnect(250)
}

In the above sample code, we create an MQTT client instance and connect to the MQTT server using the Connect() method. Then, we performed the subscribe and publish operations after the connection was successful. You can customize the topic, message content and QoS level according to actual needs

Guess you like

Origin blog.csdn.net/m0_73728511/article/details/133255956