代码拉取完成,页面将自动刷新
Mix.install([
{:emqtt, github: "emqx/emqtt", tag: "1.8.3"}
])
require Logger
Process.flag(:trap_exit, true)
topic = "topic-#{:rand.uniform(9999999)}-#{:erlang.system_time(:millisecond)}"
{:ok, subscriber} = :emqtt.start_link(
host: "broker.emqx.io",
port: 1883,
client_id: "elixir_subscriber",
username: "user",
password: "password"
)
{:ok, _} = :emqtt.connect(subscriber)
qos1_granted = 1
{:ok, %{} = _props, [^qos1_granted]} = :emqtt.subscribe(subscriber, topic, :qos1)
{:ok, publisher} = :emqtt.start_link(
host: "broker.emqx.io",
port: 1883,
client_id: "elixir_publisher",
username: "user",
password: "password"
)
{:ok, _} = :emqtt.connect(publisher)
:ok = :emqtt.publish(publisher, topic, "qos0_message", :qos0)
{:ok, %{reason_code: 0}} = :emqtt.publish(publisher, topic, "qos1_message", :qos1)
{:ok, %{reason_code: 0}} = :emqtt.publish(publisher, topic, "qos2_message", :qos2)
for _ <- 1..3 do
receive do
msg ->
Logger.info("Received message: #{inspect(msg)}")
after
1000 ->
Logger.error("Message not received")
Logger.flush()
System.halt(1)
end
end
:emqtt.disconnect(subscriber)
:emqtt.disconnect(publisher)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。