MQTT

2019-02-27

MQTT服务端 EMQ X

官网下载地址:https://www.emqx.io/downloads

端口修改

1883	MQTT端口
8883	MQTT / SSL端口
8083	MQTT / WebSocket端口
8084	MQTT / WebSocket / SSL端口
8080	HTTP管理API端口
18083	Web仪表板端口

使用的TCP端口可以在etc/emqx/emqx.conf中配置:

## TCP Listener: 1883, 127.0.0.1:1883, ::1:1883
listener.tcp.external = 0.0.0.0:1883

## SSL Listener: 8883, 127.0.0.1:8883, ::1:8883
listener.ssl.external = 8883

## External MQTT/WebSocket Listener
listener.ws.external = 8083

## HTTP Management API Listener
listener.api.mgmt = 127.0.0.1:8080

Web仪表板端口18083可以在etc/emqx/plugins/emqx_dashboard.conf中配置:

## The IP address and port that the Dashboard HTTP listener will bind.
dashboard.listener.http = 18083

Web仪表板默认登录:admin,密码:public

websocket端口修改,在etc/emqx/emqx.conf中配置:

## Examples: 8083, 127.0.0.1:8083, ::1:8083
listener.ws.external = 8083

listener.wss.external = 8084

启动服务

service emqx start

开启订阅、发布权限认证

1.首先关闭匿名权限,在etc/emqx/emqx.conf中配置:

allow_anonymous = false

2.接下来去,etc/emqx/plugins目录下编辑文件emq_auth_username.conf,添加用户名和密码,保存并退出:

auth.user.1.username = t1

auth.user.1.password = t1password

3.开启用户密码认证插件

第一种方式:emqttd_ctl plugins load emq_auth_username

第二种方式:在 web 管理控制台中开启该插件

4.重启服务,使插件生效

ACL控制用户权限

配置好了用户,接下来可以通过ACL精确控制每个用户权限

比如编辑etc/emqx/acl.conf :

{allow, {user, "t1"}, subscribe, ["mqtt/demo"]}.
{allow, {user, "t2"}, publish, ["mqtt/demo"]}.
{deny, all}.

以上分别开启t1、t2用户的订阅、发布mqtt/demo主题权限。

重启服务,使ACL配置生效

MQTT服务端 Mosquitto

安装 mosquitto

apt install mosquitto

增加用户test,设置密码

mosquitto_passwd -c /etc/mosquitto/passwd test

编辑配置文件 /etc/mosquitto/mosquitto.conf

修改监听端口

listener 1234

启动

mosquitto -c /etc/mosquitto/mosquitto.conf

MQTT 客户端

1.桌面客户端

mqttx

https://mqttx.app/zh/downloads

2.WEB客户端

paho-mqtt.js

官网:https://github.com/eclipse/paho.mqtt.javascript

MQTT.js

官网:https://github.com/mqttjs/MQTT.js

eg:

<html>
<head>
    <title>test Ws mqtt.js</title>
</head>
<body>
    <script src="mqtt.min.js"></script>
    <script>
        var client = mqtt.connect('ws://mqtt.malu.me/mqtt') // you add a ws:// url here
        client.subscribe("mqtt/demo")

        client.on("message", function (topic, payload) {
            alert([topic, payload].join(": "))
        })

        client.publish("mqtt/demo", "hello world!")
    </script>
</body>
</html>

3.Linux客户端

安装

apt install mosquitto-clients

订阅

mosquitto_sub -h localhost -t mqtt -u test -P 123456

发布

mosquitto_pub -h localhost -t mqtt -m "hello world" -u test -P 123456

-h参数指定要连接的MQTT服务器

-t参数指定向指定主题推送消息

-m参数指定消息内容

-r参数保留消息

eg.自动通知在线时间脚本

mosquitto_pub -h soldier.cloudmqtt.com -p 16885 -u test -P test -t 1 -r -m "`uptime`"

MQTT Free server

汇总 Public brokers

https://github.com/mqtt/mqtt.github.io/wiki/public_brokers

mosquitto

https://test.mosquitto.org/

hivemq

https://broker.hivemq.com/

cloudmqtt

https://customer.cloudmqtt.com/login

solace

https://console.solace.cloud/login/

cloudamqp

https://customer.cloudamqp.com/instance

emqx

https://www.emqx.com/