赞
踩
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto
sudo apt-get install mosquitto-dev
sudo apt-get install mosquitto-clients
sudo service mosquitto status
active则为正常运行

| 参数 | 说明 |
|---|---|
-h | 服务器主机,默认localhost |
-p | 端口号,默认1883 |
-t | 指定主题 |
-u | 用户名 |
-P | 密码 |
-i | 客户端id,唯一 |
-m | 发布的消息内容 |
mosquitto_sub -h localhost -t "mqtt" -v
需要另开一个终端,当执行完下面命令后,会在上一个终端出打印出我们发布的消息
mosquitto_pub -h localhost -t "mqtt" -m "Hello MQTT"
设置一下用户名和密码,这样我们的mqtt才会比较安全。mqtt总配置在
/etc/mosquitto/mosquitto.conf中
在该文件末尾添加下面三个配置
# 关闭匿名
allow_anonymous false
# 设置用户名和密码
password_file /etc/mosquitto/pwfile
# 配置访问控制列表(topic和用户的关系)
acl_file /etc/mosquitto/acl
# 配置端口
port 8000
添加一个用户,用户名为
pibigstar,这个命令执行之后会让你输入密码,密码自己定义就好
sudo mosquitto_passwd -c /etc/mosquitto/pwfile pibigstar
新增acl文件
sudo vim /etc/mosquitto/acl
添加下面内容
# 用户test只能发布以test为前缀的主题
# 订阅以mqtt开头的主题
user test
topic write test/#
topic read mqtt/#
user pibigstar
topic write mqtt/#
topic write mqtt/#
sudo /etc/init.d/mosquitto restart
mosquitto_sub -h 127.0.0.1 -p 8000 -t "mqtt" -v -u pibigstar -P 123456
mosquitto_pub -h 127.0.0.1 -p 8000 -t "mqtt" -m "Hello MQTT" -u pibigstar -P 123456
package mqtt import ( "encoding/json" "errors" "fmt" "strings" "sync" "time" gomqtt "github.com/eclipse/paho.mqtt.golang" ) const ( Host = "192.168.1.101:8000" UserName = "pibigstar" Password = "123456" ) type Client struct { nativeClient gomqtt.Client clientOptions *gomqtt.ClientOptions locker *sync.Mutex // 消息收到之后处理函数 observer func(c *Client, msg *Message) } type Message struct { ClientID string `json:"clientId"` Type string `json:"type"` Data string `json:"data,omitempty"` Time int64 `json:"time"` } func NewClient(clientId string) *Client { clientOptions := gomqtt.NewClientOptions(). AddBroker(Host). SetUsername(UserName). SetPassword(Password). SetClientID(clientId). SetCleanSession(false). SetAutoReconnect(true). SetKeepAlive(120 * time.Second). SetPingTimeout(10 * time.Second). SetWriteTimeout(10 * time.Second). SetOnConnectHandler(func(client gomqtt.Client) { // 连接被建立后的回调函数 fmt.Println("Mqtt is connected!", "clientId", clientId) }). SetConnectionLostHandler(func(client gomqtt.Client, err error) { // 连接被关闭后的回调函数 fmt.Println("Mqtt is disconnected!", "clientId", clientId, "reason", err.Error()) }) nativeClient := gomqtt.NewClient(clientOptions) return &Client{ nativeClient: nativeClient, clientOptions: clientOptions, locker: &sync.Mutex{}, } } func (client *Client) GetClientID() string { return client.clientOptions.ClientID } func (client *Client) Connect() error { return client.ensureConnected() } // 确保连接 func (client *Client) ensureConnected() error { if !client.nativeClient.IsConnected() { client.locker.Lock() defer client.locker.Unlock() if !client.nativeClient.IsConnected() { if token := client.nativeClient.Connect(); token.Wait() && token.Error() != nil { return token.Error() } } } return nil } // 发布消息 // retained: 是否保留信息 func (client *Client) Publish(topic string, qos byte, retained bool, data []byte) error { if err := client.ensureConnected(); err != nil { return err } token := client.nativeClient.Publish(topic, qos, retained, data) if err := token.Error(); err != nil { return err } // return false is the timeout occurred if !token.WaitTimeout(time.Second * 10) { return errors.New("mqtt publish wait timeout") } return nil } // 消费消息 func (client *Client) Subscribe(observer func(c *Client, msg *Message), qos byte, topics ...string) error { if len(topics) == 0 { return errors.New("the topic is empty") } if observer == nil { return errors.New("the observer func is nil") } if client.observer != nil { return errors.New("an existing observer subscribed on this client, you must unsubscribe it before you subscribe a new observer") } client.observer = observer filters := make(map[string]byte) for _, topic := range topics { filters[topic] = qos } client.nativeClient.SubscribeMultiple(filters, client.messageHandler) return nil } func (client *Client) messageHandler(c gomqtt.Client, msg gomqtt.Message) { if client.observer == nil { fmt.Println("not subscribe message observer") return } message, err := decodeMessage(msg.Payload()) if err != nil { fmt.Println("failed to decode message") return } client.observer(client, message) } func decodeMessage(payload []byte) (*Message, error) { message := new(Message) decoder := json.NewDecoder(strings.NewReader(string(payload))) decoder.UseNumber() if err := decoder.Decode(&message); err != nil { return nil, err } return message, nil } func (client *Client) Unsubscribe(topics ...string) { client.observer = nil client.nativeClient.Unsubscribe(topics...) }
package mqtt import ( "encoding/json" "fmt" "sync" "testing" "time" ) func TestMqtt(t *testing.T) { var ( clientId = "pibigstar" wg sync.WaitGroup ) client := NewClient(clientId) err := client.Connect() if err != nil { t.Errorf(err.Error()) } wg.Add(1) go func() { err := client.Subscribe(func(c *Client, msg *Message) { fmt.Printf("接收到消息: %+v \n", msg) wg.Done() }, 1, "mqtt") if err != nil { panic(err) } }() msg := &Message{ ClientID: clientId, Type: "text", Data: "Hello Pibistar", Time: time.Now().Unix(), } data, _ := json.Marshal(msg) err = client.Publish("mqtt", 1, false, data) if err != nil { panic(err) } wg.Wait() }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。