2016-10-15 228 views
0

我正在使用MQTT Paho項目中的以下代碼來訂閱來自我的mqtt代理的消息。我使用mosquitto_sub測試了連接,並在那裏收到消息。但是,當我運行下面的代碼時,它不會收到任何消息並且沒有輸出被打印。我檢查了主題和主機。由經紀人登錄MQTT客戶端未收到消息

import paho.mqtt.client as mqtt 

# The callback for when the client receives a CONNACK response from the server. 
def on_connect(client, userdata, rc): 
    print("Connected with result code "+str(rc)) 
    # Subscribing in on_connect() means that if we lose the connection and 
    # reconnect then subscriptions will be renewed. 
    client.subscribe("test") 

# The callback for when a PUBLISH message is received from the server. 
def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 

client = mqtt.Client() 

client.on_connect = on_connect 
client.on_message = on_message 

client.connect("localhost", 1883, 60) 
client.loop_forever() 

以下錯誤:

Invalid protocol "MQTT" in CONNECT from ::1. 
Socket read error on client (null), disconnecting. 

編輯感謝@hardillb您指出過時的MQTT版本。

一切工作我做了以下後:

  1. sudo易於得到淨化mosquitto
  2. sudo易於添加存儲庫PPA:mosquitto-dev /目錄mosquitto-PPA
  3. sudo易於得到更新
  4. 命令和apt-get安裝mosquitto
+0

當你說不起作用時,你會得到任何輸出嗎?你在哪個平臺上運行這個? – hardillb

+0

完全沒有輸出。 – Andrei

+0

如果你甚至沒有得到「連接結果代碼...」的消息,那麼你應該檢查代理日誌,看看它是否顯示客戶端沒有連接的原因。您發佈的代碼在此處正常工作 – hardillb

回答

1

這很可能是因爲您使用的是舊版本mosquitto和蟒蛇爲e xpecting支持MQTT一個新的構建3.1.1

嘗試更改代碼如下所示:

import paho.mqtt.client as mqtt 

# The callback for when the client receives a CONNACK response from the server. 
def on_connect(client, userdata, rc): 
    print("Connected with result code "+str(rc)) 
    # Subscribing in on_connect() means that if we lose the connection and 
    # reconnect then subscriptions will be renewed. 
    client.subscribe("test") 

# The callback for when a PUBLISH message is received from the server. 
def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 

# Change made HERE 
client = mqtt.Client(protocol=MQTTv31) 

client.on_connect = on_connect 
client.on_message = on_message 

client.connect("localhost", 1883, 60) 
client.loop_forever() 

你也應該儘快升級你的經紀人,那個版本是非常過時的,並擁有多項已知問題,當前版本是1.4.10

相關問題