【发布时间】:2022-01-06 17:59:13
【问题描述】:
我有基于 Python Tkinter UI 的项目。我使用 mqtt 发布者从文本框发送消息,并使用同一个客户端同时收听它们。它可以工作,但无限监听循环在收到消息后使我的应用程序崩溃。
我的问题可能就在这里
while 1:
client.loop(timeout=1, max_packets= 2) #contineously checking for message
尝试使用 loop(timeout,maxpackage) 但没用,或者我做错了。
全部功能
def func_sendanswer():
def func_refreshconversation():
conn = psycopg.connect("dbname=MQTTDB user=postgres host='localhost' password='pw123'")
cur = conn.cursor()
cur.execute("SELECT answercontent, creatorid, createddate FROM answers WHERE topicid ='"+ str(temp[0]) +"';")
temp2 = cur.fetchall()
text_conversation.delete("1.0","end")
for row in temp2:
text_conversation.insert(END, "\n" + "Kullanıcı ID: " + str(row[1]) + "\n" + "\n" + str(row[0]) +"\n" + "Tarih: " + str(row[2]) + "\n" + "___________________________________________________" + "\n")
cur.close()
conn.close()
message = text_sendmessage.get('0.0', 'end')
tpcname = string_topicname
print(string_topicname)
def on_message(client, userdata, message):
print("Gelen Mesaj:")
print(str(message.payload.decode("utf-8")) )
msj = str(message.payload.decode("utf-8"))
print("")
conn = psycopg.connect("dbname=MQTTDB user=postgres host='localhost' password='pw123'")
cur = conn.cursor()
cur.execute('INSERT INTO answers(answercontent, creatorid, topicid, createddate) VALUES (%s,%s,%s,current_timestamp)', (msj, online_userid, topicid))
conn.commit()
cur.close()
conn.close()
func_refreshconversation()
client= paho.Client("user") #create client object
client.on_message=on_message
print("connecting to broker host","localhost")
client.connect("localhost")#connection establishment with broker
print("subscribing begins here")
client.subscribe(tpcname)#subscribe topic test
ret= client.publish(tpcname,message) #topic name is test
while 1:
client.loop(timeout=1, max_packets= 2) #contineously checking for message
【问题讨论】:
-
这里的意图到底是什么,你是打算在收到消息后完全断开客户端,还是打算在收到消息后继续发布?还是只是为了不阻止用户界面?
-
@hardillb 是的,我只想获得一条消息,而不是阻止 UI。因为上面的功能是通过按钮触发的,所以我不需要一直听。
标签: python python-3.x mqtt