mosquitto官网
下载源码:
wget https://mosquitto.org/files/source/mosquitto-1.6.12.tar.gz
解压源码:
tar -xzvc mosquitto-1.6.12.tar.gz
修改配置文件
cd mosquitto-1.6.12
vim config.mk
修改安装路径,这个/home/soft/mosquitto是自己要安装的位置
prefix?=/home/soft/mosquitto
编译安装
sudo make && make install
安装完成后可以看到目录下面有这些目录
bin include lib sbin share
创建配置文件目录
cd /home/soft/mosquitto
mkdir conf
将配置文件拷贝到conf
mv /etc/usr/mosquitto/* conf
cp mosquitto.conf.example mosquitto.conf
将so文件拷贝到系统路径
sudo ln -s /home/soft/mosquitto/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
启动
./sbin/mosquitto -c ./conf/mosquitto.conf -d
检查是否启动
ps -ef | grep mosquitto
测试
在服务器上新建两个shell,A和B
A 订阅主题:
./bin/mosquitto_sub -t topicA
B 推送消息:
./bin/mosquitto_pub -t topicA -h localhost -m “topicA test”
go语言Demo代码
package main
import (
"fmt"
"github.com/eclipse/paho.mqtt.golang"
"os"
"os/signal"
)
var defaultMsgHandle mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
var myMsgHandle mqtt.MessageHandler = func (client mqtt.Client, msg mqtt.Message) {
fmt.Printf("mytopic: %s, msg: %s\n", msg.Topic(), msg.Payload())
}
func main() {
opts := mqtt.NewClientOptions().AddBroker("tcp://192.168.9.215:1883")
opts.SetClientID("go-simple")
opts.SetAutoReconnect(true)
opts.SetDefaultPublishHandler(defaultMsgHandle)
mqttClient := mqtt.NewClient(opts)
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//订阅消息
if token := mqttClient.Subscribe("topicA", 0, myMsgHandle); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
//发送5个消息
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
token := mqttClient.Publish("topicA", 0, false, text)
token.Wait()
}
//保证main函数不退出
ch := make(chan os.Signal)
signal.Notify(ch, os.Interrupt, os.Kill)
signalCh := <-ch
fmt.Println("退出信号", signalCh)
//取消订阅
if token := mqttClient.Unsubscribe("topicA"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
//关闭连接
mqttClient.Disconnect(250)
}