【问题标题】:error during running this python code (mqtt)运行此 python 代码(mqtt)时出错
【发布时间】:2019-07-28 16:26:51
【问题描述】:

在运行此代码期间

import paho.mqtt.client as pub

c = pub.Client()

c.connect("broker.hivemq.com",1833)

while True:

    c.publish("room1","hello!welcome to iot class")
Traceback (most recent call last):
  File "C:\Users\Sukreeti\Desktop\mqtt\publish.py", line 3, in <module>
    c.connect("broker.hivemq.com",1833)
  File "C:\Users\Sukreeti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\paho\mqtt\client.py", line 839, in connect
    return self.reconnect()
  File "C:\Users\Sukreeti\AppData\Local\Programs\Python\Python37-32\lib\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 "C:\Users\Sukreeti\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 727, in create_connection
    raise err
  File "C:\Users\Sukreeti\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 716, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

【问题讨论】:

  • 首先找到一个体面的示例,该示例实际处理(重新)连接并且不会尝试通过不断发送相同的消息来阻塞通道。还要确保您拥有正确的代理详细信息,尤其是因为它希望需要 ssl 和凭据才能访问。

标签: mqtt iot publish-subscribe


【解决方案1】:

即使您发布的代码确实有效,它实际上也是对代理的 DoS 攻击,而不是您应该对提供给人们进行测试的免费公共代理做的事情。

由于您没有启动network loop 线程,将导致此问题。该线程处理代理发回给客户端的所有消息,例如连接确认。

我建议您阅读 Paho 文档的 Getting Started 部分,但这里是您发布的内容的更好版本,它只会发布一条消息。

import paho.mqtt.client as pub

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("room1")
    client.publish("room1", "hello!welcome to iot class")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))


c = pub.Client()
c.on_connect = on_connect
c.on_message = on_message

c.connect("broker.hivemq.com",1833)
c.loop_forever() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2022-11-07
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多