安装依赖
首先,我们需要安装Golang的依赖包来支持MQTT服务器的搭建。Golang具有丰富的开源库和包管理器,使得我们可以方便地构建应用程序和服务器。通过以下命令来安装paho.mqtt.golang库:
go get -u github.com/eclipse/paho.mqtt.golang
搭建MQTT服务器
接下来,让我们开始编写Golang代码来搭建MQTT服务器。首先,导入必要的依赖包。package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
创建一个函数用于处理MQTT客户端的连接和发布消息:
// 连接处理函数
func connHandler(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("接收到来自 %s 的消息:%s\n", msg.Topic(), string(msg.Payload()))
}
// 发布消息
func publish(client mqtt.Client, topic string, payload string) {
token := client.Publish(topic, 0, false, payload)
token.Wait()
fmt.Printf("发布消息到主题 %s 成功!\n", topic)
}
// 主程序
func main() {
opts := mqtt.NewClientOptions().AddBroker("tcp://127.0.0.1:1883")
opts.SetClientID("mqtt-server")
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatal(token.Error())
}
fmt.Println("MQTT服务器已启动!")
client.Subscribe("test", 0, connHandler)
// 等待程序退出
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
client.Disconnect(250)
fmt.Println("MQTT服务器已停止!")
}
使用MQTT服务器
现在,我们可以开始使用我们搭建的MQTT服务器了。以下是一些常见的使用场景和示例代码:发布消息:
// 创建一个MQTT客户端实例
client := mqtt.NewClient(opts)
// 连接到MQTT服务器
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatal(token.Error())
}
// 发布消息到主题 "test"
publish(client, "test", "Hello, MQTT!")
// 断开与MQTT服务器的连接
client.Disconnect(250)
订阅主题:
client.Subscribe("test", 0, connHandler)