您需要在connect()函数中传递要连接的代理的详细信息
例如
...
client.on_message = on_message
client.connect('broker.example.com')
client.subscribe(topic)
...
编辑:您还需要启动网络循环.给定这是flask应用程序,您将需要在后台启动循环,因此请使用loop_start函数.
...
client.connect('broker.example.com')
client.loop_start()
...
您还应该将订阅和发布调用移至on_connect回调,因为它们需要等待连接建立后才能运行.
EDIT2:添加完整的工作代码:
from flask import Flask
import paho.mqtt.client as mqtt
app = Flask(__name__)
topic = 'foo'
topic2 = 'bar'
port = 5000
def on_connect(client, userdata, rc):
client.subscribe(topic)
client.publish(topic2, "STARTING SERVER")
client.publish(topic2, "CONNECTED")
def on_message(client, userdata, msg):
client.publish(topic2, "MESSAGE")
@app.route('/')
def hello_world():
return 'Hello World! I am running on port ' + str(port)
if __name__ == '__main__':
client = mqtt.Client()
#client.username_pw_set(username, password)
client.on_connect = on_connect
client.on_message = on_message
client.connect('localhost')
client.loop_start()
app.run(host='0.0.0.0', port=port)