我写了一个简单的python程序来连接RabbitMqtt
服务器,希望生成一个队列并发布消息。但是,在构建连接并创建队列之后,消息未成功发布(当我检查消息的信息时,我找不到任何记录和数据)。我想知道我错过了client.publish()
中的一些参数或设置,但我不知道如何解决这个问题。
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, 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('SEEDQ')
client.publish('SEEDQ', 'deqwdqwefqwefwefqwefqwe', 0, False)
# 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("15.78.xx.xx", 1883, 60)
client.loop_forever()
答案 0 :(得分:1)
问题是您在连接完成之前调用client.publish()。将client.publish移动到on_connect函数,在client.subscribe(' SEEDQ')之后,它将起作用。
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, 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("$SYS/#")
client.subscribe('SEEDQ')
client.publish('SEEDQ', 111, 0, False)
输出:
Connected with result code 0
SEEDQ 111
仅供参考我在iot.eclipse.org,端口1883使用了公共测试服务器。
仅供参考,有一个非常有用的浏览器客户端HERE - 使用此公共测试服务器messagesight.demos.ibm.com端口1883您可以订阅SEEDQ并查看您的python脚本发布,并使用浏览器客户端可以从浏览器发布到SEEDQ,并且脚本将在loop_forever()中显示消息。显然,使用这些测试服务器是公开可见的。
UPDATE这里是完整的代码 - 这对我上面显示的公共服务器起作用。
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, 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("$SYS/#")
client.subscribe('SEEDQ')
client.publish('SEEDQ', 111, 0, False)
# 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('15.xx.xx.xx', 1883, 60)
#client.connect("iot.eclipse.org", 1883, 60)
client.connect("messagesight.demos.ibm.com", 1883, 60)
#client.publish('SEEDQ', 111, 0, False)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()