Elv*_*rov 5 python multithreading python-multithreading python-3.x mqtt
我有如下代码
threads = []
t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start)
t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start)
threads.append(t)
threads.append(t1)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Run Code Online (Sandbox Code Playgroud)
我的主题每 5 分钟发送一次数据。
当我使用上面的代码时,它无法正常工作,有时发送数据有时不发送数据。
但是,当我使用一个没有线程的主题时,它工作正常,并且数据每 5 分钟完美地传入一次。
我怎么解决这个问题?我想同时订阅两个主题。
我正在使用Paho进行MQTT
我的订阅类别是
class Subscribe:
def __init__(self, username, passowrd, topic, host, port):
self.username = username
self.password = passowrd
self.topic = topic
self.host = host
self.port = port
def start(self):
self.mqttc = mqtt.Client(client_id="Python")
self.connected = False
self.mqtt_message = ""
self.mqttc.username_pw_set(self.username, self.password)
self.mqttc.on_connect = self.on_connect
self.mqttc.on_message = self.on_message
self.mqttc.connect(self.host, self.port)
self.mqttc.loop_forever()
def on_message(self, client, userdata, message):
"""
Fetch data when data coming to Broker
"""
topic = message.topic
m = json.loads(message.payload.decode("utf-8"))
print(m)
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Connected to broker", self.topic)
self.mqttc.subscribe(self.topic)
self.connected = True
else:
print("could not connect", self.topic)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
542 次 |
| 最近记录: |