当我运行 sub_file.py 程序时,出现如下错误:
AttributeError: 'NoneType' object has no attribute 'recv'
这是 sub_file.py 代码:
import time
import paho.mqtt.client as mqtt #import the client1
import base64
broker_address="mqtt.eclipseprojects.io"
port = 1883
client = mqtt.Client("P2") #create new instance
client.connect(broker_address,port) #connect to broker
def on_message(cln, obj, msg):
print("new message")
data = msg.payload.decode()
msg = str(data)
img = msg.encode('ascii')
with open('iris.jpg', 'wb') as fd:
final_data = base64.b64decode(img)
fd.write(final_data)
fd.close()
def on_subscribe(client, userdata, mid, granted_qos):
print("subscribe success")
client.subscribe("photo_topic_file")
client.on_subscribe = on_subscribe
print("Subscribing...")
client.loop_start()
client.on_message = on_message
client.loop_forever()
这是 pub_file.py 代码:
import paho.mqtt.client as mqtt
import base64
import time
broker_address="mqtt.eclipseprojects.io"
port = 1883
client = mqtt.Client("P1")
f = open("data.jpg", "rb")
isi_file = f.read()
convert_result_ke_base64 = base64.b64encode(isi_file)
client.connect(broker_address, port)
client.loop_start()
result = client.publish("photo_topic_file", convert_result_ke_base64)
if result[0] == 0:
print("publish success")
else:
print("publish failed")
time.sleep(5)
client.loop_stop()
当我运行 pub_file.py 时,程序正常工作,但是当我运行 sub_file.py 时,它显示错误
有人可以解决这个问题吗?
client.on_subscribe = on_subscribe
print("Subscribing...")
client.loop_start()
client.on_message = on_message
client.loop_forever()
您正在启动两个消息循环:
client.loop_start()
client.loop_forever()
这会导致问题,因为编写代码时假设只有一个消息循环将运行。
解决此问题的最简单方法是删除
client.loop_start()
。
请注意,最好从
subscribe
调用 on_connect
,如“入门”所示。我还建议在调用 connect
之前设置回调(在启动循环后设置 on_message
可能会导致消息丢失)。