MQTT

2019-02-27

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 客户端

1.MQTTBox

官网:http://workswithweb.com

2.WEB客户端

官网: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>