环境: centos 7, python3
1 安装消息中间件mosquitto
下载源文件
http://mosquitto.org/download/
编译安装
make
sudo make install
可执行命令文件放在
/usr/local/bin
/usr/local/sbin
配置文件放在
/etc/mosquitto
自定义配置文件 mosquitto.conf
cp mosquitto.conf.example mosquitto.conf
修改端口位 1883
启动服务
/usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
2 server
server.py
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("chat")
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("127.0.0.1", 1883, 60)
client.loop_forever()
运行
python3 server.py
3 client
client.py
import paho.mqtt.client as mqtt
HOST = "127.0.0.1"
PORT = 1883
def test():
client = mqtt.Client()
client.connect(HOST, PORT, 60)
client.publish("chat","hello chenfulin",2)
client.loop_forever()
if __name__ == '__main__':
test()
运行
python3 client.py
server 程序将会打印 client 发送的数据。