【问题标题】:Python paho-mqtt blocking client loopPython paho-mqtt 阻塞客户端循环
【发布时间】:2020-01-18 08:17:55
【问题描述】:

目前我正在尝试编写一个程序来模拟产生以下代码的攻击:

import requests
import threading
import paho.mqtt.client as mqtt

class Attack(object):

    def __init__(self):

        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

        self.client.connect("test.mosquitto.org")
        self.client.loop_forever()

    def poll_heise(self):
        while(True):
            time.sleep(2)
            r = requests.get('https://heise.de')

    def on_connect(self):
        self.client.subscribe("ATTACK")
        thread = threading.Thread(target=self.poll_heise)
        thread.start()

    def on_message(self):
        for i in range(1,80):
            thread = threading.Thread(target=self.write_file,args=(i,))
            thread.start()

    def write_file(self,suffix):
        new_file = open("file{0}".format(suffix),"w")
        new_file.write("testtesttesttest")
        new_file.close()


if __name__ == "__main__":
    attack = Attack()

基本上,我想要做的是生成一种独特的行为,并保持这种行为(例如,使用请求轮询 heise.de),然后在主题“ATTACK”的 MQTT 消息到达时中断这种行为。

但是,当我启动代码并尝试通过在“ATTACK”上发布到 test.mosquitto.org 来触发 on_message 方法时,我什么也得不到。据我所知,解释器甚至没有到达 on_message 回调。我尝试手动发布和订阅 mqtt 代理,并且成功了。

有人知道为什么这不起作用吗?

_ 编辑: 我怀疑这是我处理线程或某个循环阻塞的方式的问题,但我无法确定它是哪一个。非常感谢。

【问题讨论】:

    标签: python-3.x mqtt python-multithreading paho


    【解决方案1】:

    self.client.loop_forever() 行是一个阻塞调用,所以你的__init__ 函数永远不会返回。

    改为查看client.start_loop() 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 2018-03-17
      • 2016-10-27
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多