python - 通过 Python 发布 MQTT:[Errno 101] 网络不可达
问题描述
我已经使用此脚本在本地网络中的 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
解决方案
- 您可能会遗漏在 url 中提及协议部分,例如
tcp://website.io
. 对于websocket tcp或ssl应该正确提及。 - 还要检查防火墙中的出站流量规则。
sudo ufw status
添加您允许无处不在的通信协议。
推荐阅读
- python - 使用 Tensorflow 生成随机布尔值
- google-sheets - 在 Google 表格中使用 {} 运算符加入 2 个动态范围
- python - TypeError:“BitStream”对象不能解释为整数
- python - How to properly nest many ttk.PanedWindow one in other?
- android - 如何在不重新启动服务的情况下将意图从片段发送到服务
- reactjs - axios 请求,从错误对象中读取验证消息
- rest - Restemplate 无法设置通用基本身份验证标头
- javascript - 如何将输入类型=“周”的值转换为时间戳?
- python - Python - 找不到包
- javascript - 如何在 Angular 10 中创建圆形菜单?