---
title: "mosquitto 基于MQTT消息推送"
author: "ipython"
date: "2016-07-15T12:56:36Z"
tags: []
categories: ["移动开发"]
slug: "mosquitto-mqtt"
draft: false
lastmod: "2016-07-15T13:02:36Z"
id: 2311457
url: "https://ipython.iteye.com/blog/2311457"
---

mosquitto note  
基于MQTT消息推送\[[https://mosquitto.org](https://mosquitto.org)]

### [](#_1)目的

```
* 要解决的问题是：给Android手机做消息推送
* 不使用第三方的SDK,如极光推送，百度云推送，信鸽 这些都不能用
* 自已搭建消息推送后台
```

### [](#_2)模块

```
* 代理端（中转消息，守护进程) mosquitto
* 发送消息客户端 mosquitto_pub
* 接收消息客户端 mosquitto_sub
* 管理密码文件  mosquitto_passwd
```

### [](#ubuntu)Ubuntu安装

```
* sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
* sudo apt-get update 
* sudo apt-get install mosquitto   mosquitto-clients
* 开机启动 chkconfig mosquitto on
```

### [](#_3)测试

```
* 先启动服务进程    mosquitto -d
* 订阅某个频道(news)的消息(监听)  mosquitto_sub -t news
* 发送消息(hello)到某个频道(news)    mosquitto_pub -t news -m "hello"
* 可以观察到当mosquitto_pub之后，可以在mosquitto_sub看到刚才发送的消息
```

### [](#_4)配置

```
* 配置文件路径 /etc/mosquitto/mosquitto.conf
* 启动服务进程mosquitto，除了可能用命令行参数，还要以通过配置文件，配置文件更为详细。
* 可以指定ip地址和端口，还可以使用用户名和密码
* 可以添加加密码证书
```

### [](#_5)案例

#### [](#_6)使用密码

````
* 创建只读用户user1和可写用户user2和密码都为user1234
    ** mosquitto_passwd -c /etc/mosquitto/pawd user1     // -c 表示新增一个文件，如果创建第二个用户，不需要-c
    ** mosquitto_passwd /etc/mosquitto/pawd user2 
* 修改配置文件,不允许匿名用户，指定存储用户名和密码的文件路径，和用户读写权限的文件
    ** 创建自己的配置文件, touch /etc/mosquitto/conf.d/my.conf
    ```
        allow_anonymous false
        password_file /etc/mosquitto/pawd
        acl_file /etc/mosquitto/acl
    ```
    ** 创建用户读写权限的文件/etc/mosquitto/acl
    ```
        user user1
        topic read news

        user user2
        topic write news
    ```
* 测试
    ** sudo service mosquitto restart
    ** mosquitto_sub -t news -u user1 -P user1234
    ** mosquitto_pub -t news -m "hello" -u user2 -P user1234
    
````