package main

import (
    "fmt"
    "time"

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

// 连接的回掉函数
var connectHandler MQTT.OnConnectHandler = func(client MQTT.Client) {
    fmt.Println("新的连接!" + " Connected")
}

// 丢失连接的回掉函数
var connectLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err error) {
    fmt.Printf("Connect loss: %v\n", err)
}
var messagePubHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
    fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

func main() {
    opts := MQTT.NewClientOptions().AddBroker("tcp://:1883").SetClientID("test_push")
    opts.SetUsername("emqx")
    opts.SetPassword("public")

    opts.SetKeepAlive(60 * time.Second)
    opts.SetPingTimeout(1 * time.Second)
    opts.OnConnect = connectHandler
    opts.SetDefaultPublishHandler(messagePubHandler)
    opts.OnConnectionLost = connectLostHandler
    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }
    var (
        name    string
        age     int
        married bool
    )
    fmt.Scan(&name, &age, &married)
    fmt.Printf("扫描结果 name:%s age:%d married:%t\t", name, age, married)
}

 

posted on 2022-04-20 17:16  金科许俊  阅读(517)  评论(0编辑  收藏  举报