【问题标题】:MQTT not connecting?MQTT 无法连接?
【发布时间】:2019-08-10 22:33:54
【问题描述】:

我目前正在尝试使用 paho.mqtt 库设置一个简单的 MQTT 订阅者...

类似的东西

import paho.mqtt.client as mqtt
hostname = "mqtt://localhost:1883"
client = mqtt.Client(hostname, True, None, mqtt.MQTTv31)
client.connect(hostname)
client.subscribe("hermes/#")

def on_message(client, userdata, message):
    print("message received " ,str(message.payload.decode("utf-8")))
    print("message topic=",message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)

client.on_message=on_message
client.loop_forever()

给我这个错误:

Traceback (most recent call last):
  File "bedroom.py", line 5, in <module>
    client.connect(hostname)
  File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 839, in connect
    return self.reconnect()
  File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 962, in reconnect
    sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

我不明白,为什么没有连接? 我在java中有类似的脚本,它没有任何问题?

【问题讨论】:

  • 我怀疑你的 hostname 有问题,或者你的机器上有一些奇怪的网络配置,导致它无法解析地址。

标签: python python-3.x mqtt paho


【解决方案1】:

来自帕霍蟒docs

connect()

connect(host, port=1883, keepalive=60, bind_address="")

connect() 函数将客户端连接到代理。这是一个 阻塞功能。它采用以下参数:

主机

远程代理的主机名或 IP 地址

端口

要连接的服务器主机的网络端口。默认为 1883。请注意,基于 SSL/TLS 的 MQTT 的默认端口是 8883,因此如果您使用 tls_set() 或 tls_set_context(),端口可能需要 手动提供

...

connect() 函数采用主机名或 IP 地址。你已经通过了URI。如果您从开头删除mqtt:// 并从hostname 变量中删除:1883,它将连接。

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2021-12-27
    • 2017-01-20
    • 2015-02-22
    相关资源
    最近更新 更多