Home >Backend Development >Golang >mqtt forward golang

mqtt forward golang

PHPz
PHPzOriginal
2023-05-22 13:54:08784browse

MQTT Forwarding Golang

With the advent of the Internet of Things (IoT) era, communication between devices has become more and more important. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed to provide an efficient data exchange mechanism for unlimited devices and applications across low-bandwidth, high-latency, or unreliable network connections. . In this article, we will explore how to use Golang to create an MQTT forward proxy server so that different devices can communicate through the MQTT protocol.

We first need to install Golang. Once the installation is complete, we need to install the paho-mqtt package, which is the main library used to communicate with MQTT in Golang. We can install it with the following command:

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

Once completed, we will create a project folder named mqtt-forward, which includes a Golang file named main.go. We need to import the paho-mqtt package into our code:

import (
    "fmt"

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

Next, we need to set the MQTT client options:

opts := mqtt.NewClientOptions().AddBroker("tcp://broker.hivemq.com:1883").SetClientID("mqtt-forward")

In this example, we connect to the HiveMQ public MQTT For the proxy, select the TCP transport protocol, the port number is 1883, and set the client ID to "mqtt-forward". We can also set the username and password for the MQTT connection.

Now, we will establish an MQTT client connection and reference it through the pointer variable client of mqtt.Client type:

client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
    panic(token.Error())
}
defer client.Disconnect(250)

In this example, we use mqtt.NewClient(opts) Method creates a new version of the MQTT client and passes options. After connecting to the MQTT proxy server, we will close the MQTT client and wait up to 250 milliseconds to ensure that the connection has been successfully closed. The defer keyword is used to execute cleanup code before the function returns, this ensures that we properly close the MQTT client when not needed.

We also need to create a processing function after establishing a connection with the MQTT server in order to receive MQTT messages from the device. Received messages are categorized by MQTT topics.

func onMessageReceived(client mqtt.Client, message mqtt.Message) {
    fmt.Printf("Received message: %s from topic: %s
", message.Payload(), message.Topic())
}

In this example, we print the payload (the payload is the part that actually transmits the data) and topic of the received MQTT message.

Now, we need to subscribe to the MQTT topic. We can add a callback function to the client using the following code:

if token := client.Subscribe("testtopic/#", byte(0), onMessageReceived); token.Wait() && token.Error() != nil {
    panic(token.Error())
}

In this example, we subscribe to all topics starting with "testtopic". We set QoS to byte 0, which means the messages we receive are sent only once.

Our complete main function is as follows:

func main() {
    opts := mqtt.NewClientOptions().AddBroker("tcp://broker.hivemq.com:1883").SetClientID("mqtt-forward")
    client := mqtt.NewClient(opts)

    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }
    defer client.Disconnect(250)

    if token := client.Subscribe("testtopic/#", byte(0), onMessageReceived); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    for {
        time.Sleep(time.Second)
    }
}

func onMessageReceived(client mqtt.Client, message mqtt.Message) {
    fmt.Printf("Received message: %s from topic: %s
", message.Payload(), message.Topic())
}

After the program is started, we will connect to the MQTT broker on port 1883 through TCP, and add a callback function and subscribe to "testtopic ” All topics that begin with. Finally, we get into an infinite loop so that we can stay connected and keep receiving MQTT messages.

We can run the Golang program using the following command:

go run main.go

In summary, we have introduced how to use Golang and the paho-mqtt package to create an MQTT forward proxy server. By understanding how to connect to an MQTT broker server and subscribe to certain topics to capture messages from different devices, we have now been able to get MQTT messages from device-centric ways, which is very helpful for building IOT applications.

The above is the detailed content of mqtt forward golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:ruby to golangNext article:ruby to golang