2016-10-15 175 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

相关问题