MQTT如何在收到消息后停止循环

MQTT how to stop loop after getting message

我有 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

您的模型可能有误,Pub/Sub 不是 request/response 系统的好选择。

但如果您真的想以这种方式使用它,那么只需从主题中 subscribe/unsubscribe 而不是尝试通过搞乱循环来限制客户端的网络 activity。