MQTT Erlang client library

emqttMQTT Erlang Client Library - 图1 (opens new window) is the official client library provided by the open source MQTT Broker EMQ X, which is suitable for Erlang language.

The Erlang ecosystem has multiple MQTT Broker implementations, such as RabbitMQ, VerenMQ, EMQ X that support MQTT through plugins. However, due to the language minority, there is almost no choice for available MQTT client library. Among the Erlang client libraries included in the MQTT community, emqttMQTT Erlang Client Library - 图2 (opens new window) is the best choice .

emqtt is completely implemented by Erlang. It supports MQTT v3.1.1 and MQTT v5.0 protocol versions completely, and supports SSL one-way and two-way authentication and WebSocket connection. Another MQTT benchmark test tool emqtt_benchMQTT Erlang Client Library - 图3 (opens new window) is built based on this client library.

emqtt usage example

This example contains the complete code for Erlang’s emqtt client library connecting to EMQ X Broker, sending and receiving messages:

  1. ClientId = <<"test">>.
  2. {ok, ConnPid} = emqtt:start_link([{clientid, ClientId}]).
  3. {ok, _Props} = emqtt:connect(ConnPid).
  4. Topic = <<"guide/#">>.
  5. QoS = 1.
  6. {ok, _Props, _ReasonCodes} = emqtt:subscribe(ConnPid, {Topic, QoS}).
  7. {ok, _PktId} = emqtt:publish(ConnPid, <<"guide/1">>, <<"Hello World!">>, QoS).
  8. %% If the qos of publish packet is 0, `publish` function would not return packetid.
  9. ok = emqtt:publish(ConnPid, <<"guide/2">>, <<"Hello World!">>, 0).
  10. %% Recursively get messages from mail box.
  11. Y = fun (Proc) -> ((fun (F) -> F(F) end)((fun(ProcGen) -> Proc(fun() -> (ProcGen(ProcGen))() end) end))) end.
  12. Rec = fun(Receive) -> fun()-> receive {publish, Msg} -> io:format("Msg: ~p~n", [Msg]), Receive(); _Other -> Receive() after 5 -> ok end end end.
  13. (Y(Rec))().
  14. %% If you don't like y combinator, you can also try named function to recursively get messages in erlang shell.
  15. Receive = fun Rec() -> receive {publish, Msg} -> io:format("Msg: ~p~n", [Msg]), Rec(); _Other -> Rec() after 5 -> ok end end.
  16. Receive().
  17. {ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, <<"guide/#">>).
  18. ok = emqtt:disconnect(ConnPid).

emqtt MQTT 5.0 support

Currently, emqtt has fully supported MQTT 5.0.