【发布时间】:2019-10-07 16:27:27
【问题描述】:
我已使用此脚本在本地网络中的 MQTT 代理上测试了我的脚本:
import paho.mqtt.publish as publish
publish.single('some_topic, 'some message', hostname="192.168.1.123")
一切正常。现在我想发布到我获得凭据的实际服务器。遗憾的是,paho MQTT 脚本的所有示例都发布到本地服务器,因此我无法真正模拟我的脚本。我提供的凭据包括用户名、密码和主题。作为“主机名”,我进入了公司服务器的网站。
脚本现在说
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.username_pw_set("given_username",password="given_password")
publish.single("some_topic",'some message',hostname="example.com")
很遗憾,我收到了一个错误。
File "get_datas.py", line 18, in handle_data
publish.single("some_topic",msg,hostname="example.com")
File "/usr/local/lib/python3.6/site-packages/paho/mqtt/publish.py", line 223, in single
protocol, transport)
File "/usr/local/lib/python3.6/site-packages/paho/mqtt/publish.py", line 159, in multiple
client.connect(hostname, port, keepalive)
File "/usr/local/lib/python3.6/site-packages/paho/mqtt/client.py", line 839, in connect
return self.reconnect()
File "/usr/local/lib/python3.6/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/lib/python3.6/socket.py", line 722, in create_connection
raise err
File "/usr/local/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
OSError: [Errno 101] Network is unreachable
我写错了吗?
编辑: 好像主机名有问题。我可以通过插入服务器的 IP 地址来解决这个问题,我通过
[11:26:39] $ ping example.com
PING example.com (xx.xxx.xxx.xxx) 56(84) bytes of data.
64 bytes from example.com (xx.xxx.xxx.xxx): icmp_seq=1 ttl=53 time=43.3 ms
【问题讨论】:
-
虽然您的脚本看起来是正确的,但您需要为公司中运行的 MQTT 服务获取正确的主机名,并确保脚本可以访问该主机名。
-
@cheesus 如果要替换主机名,请使用
example.com之类的名称,因为website.io确实存在