鍍金池/ 問答/Python  網絡安全/ 【求助】python寫的mqtt client,連接apollo總是報錯 Err

【求助】python寫的mqtt client,連接apollo總是報錯 Error 10054

首先,apollo正常啟動

clipboard.png

python代碼,很簡單:

import time
import paho.mqtt.client as mqtt



def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

if __name__ == "__main__":
    client = mqtt.Client()
    client.username_pw_set(username="admins",password="password")
    client.on_connect = on_connect

    client.connect("127.0.0.1", 61613, 60)
    client.loop_start()


    #while True:
    time.sleep(1)
    client.publish(topic="message", payload="hello")

python2.7編譯器,運行后報錯

Connected to pydev debugger (build 173.4674.37)
[Errno 10054] 
Exception in thread Thread-6 (most likely raised during interpreter shutdown):
Process finished with exit code 0

回答
編輯回答
有你在

python代碼需要增加一行

import time
import paho.mqtt.client as mqtt



def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

if __name__ == "__main__":
    #client_id是必須的,并且是唯一的。否則可能會出現如下錯誤
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = mqtt.Client(client_id) #ClientId不能重復,所以使用當前時間
    
    client.username_pw_set(username="admins",password="password")
    client.on_connect = on_connect

    client.connect("127.0.0.1", 61613, 60)
    client.loop_start()


    #while True:
    time.sleep(1)
    client.publish(topic="message", payload="hello")
2018年9月18日 05:04