emqtt:在Erlang中實現的MQTT客戶端庫和命令行工具,支持MQTT v5.0 / 3.1.1 / 3.1。
下載源碼
git clone https://github.com/emqx/emqtt.git
編譯
cd emqtt & make
運行
./rebar3 shell
測試
1、初始化
{ok, ConnPid} = emqtt:start_link([{clientid, "2020"},{keepalive, 0},{proto_ver, v5},{host,"localhost"},{port,1883},{username,"SummerGao"},{password,"123456"}]).
2、建立連接
{ok, _Props} = emqtt:connect(ConnPid).
3、訂閱
SubOpts = [{qos, 1}].
{ok, _Props, _ReasonCodes} = emqtt:subscribe(ConnPid, #{}, [{<<"hello">>, SubOpts}]).
①訂閱主題:hello
②用MQTTBox向hello主題推送幾條消息:
③flush() 一下查看接收到的消息:
flush().
4、發佈
ok = emqtt:publish(ConnPid, <<"hello">>, #{}, <<"Hello World!">>, [{qos, 0}]).
發佈後,在MQTTBox訂閱後可收到推送的消息
5、取消訂閱
{ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, <<"hello">>).
6、關閉連接
ok = emqtt:disconnect(ConnPid).
7、退出
ok = emqtt:stop(ConnPid).
測試問題
- 長時間連接斷開:
** exception exit: {shutdown,nxdomain}
備註
{ok, ConnPid} = emqtt:start_link([{clientid, "2020-01-18"}, {owner, self()}, {clean_start, true}, {proto_ver, v5}, {force_ping, true}, {keepalive, 0}, {host, "localhost"}, {port, 1883}, {username, "SummerGao"}, {password, "123456"}]).