用户名密码:rw/readwrite

package main

import (
    "fmt"
    "os"
    "time"

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

var onConnect mqtt.OnConnectHandler = func(client mqtt.Client) {
    Info.Printf("Client connected: %t\n", client.IsConnected())
    // 订阅主题
    if token := client.Subscribe("const.net.cn/#", 0, nil); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
    }
}

var onMessage mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    Info.Printf("Topic: %s\n", msg.Topic())
    Info.Printf("Message: %s\n", msg.Payload())
}

var onDisconnect mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
    Info.Println("Client disconnected")
}
var onReconnect mqtt.ReconnectHandler = func(c mqtt.Client, co *mqtt.ClientOptions) {
    Info.Println("Client Reconnect.")
}

func MQTT_1884_unencrypted_authenticated() {
    opts := mqtt.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1884").SetClientID("const.net.cn")

    opts.SetKeepAlive(60 * time.Second)
    // 设置消息回调处理函数
    opts.SetDefaultPublishHandler(onMessage)
    opts.SetCleanSession(true)
    opts.SetAutoReconnect(true)
    opts.SetProtocolVersion(4) //3.1.1
    opts.SetOnConnectHandler(onConnect)
    opts.SetConnectionLostHandler(onDisconnect)
    opts.SetReconnectingHandler(onReconnect)
    opts.SetUsername("rw")
    opts.SetPassword("readwrite")

    opts.SetPingTimeout(1 * time.Second)

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

    time.Sleep(5 * time.Second)
    // 发布消息
    Info.Printf("MQTT Publish")
    token := c.Publish("const.net.cn/1", 0, false, "Hello World")
    token.Wait()

    for {
        Info.Printf("wait.")
        time.Sleep(10 * time.Second)
    }
}

运行结果:
INFO: 2021/09/06 15:10:39.721974 Client connected: true
INFO: 2021/09/06 15:10:44.723829 MQTT Publish
INFO: 2021/09/06 15:10:44.724246 wait.
INFO: 2021/09/06 15:10:45.317469 Topic: const.net.cn/1
INFO: 2021/09/06 15:10:45.317498 Message: Hello World
INFO: 2021/09/06 15:10:54.725207 wait.
INFO: 2021/09/06 15:11:04.725945 wait.
INFO: 2021/09/06 15:11:14.726876 wait.
INFO: 2021/09/06 15:11:24.727531 wait.

本文链接地址:https://const.net.cn/392.html

标签: none

添加新评论