MQTT(三)Python客户端+net客户端+net服务端 简单通信
程序员文章站
2022-06-15 14:19:01
...
在上一篇《 使用 MQTTnet 快速实现 MQTT 通信》实现net的MQTT服务端和客户端,这一篇将实现net的MQTT服务端、客户端和Python客户端的通讯。
1.在windows环境安装python、pip、paho-mqtt
2.编写python代码
#!/usr/bin/python
import paho.mqtt.client as mqtt
import time
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc)+'\n')
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload)+'\n')
client1 = mqtt.Client()
client1.username_pw_set("u001", "p001") #username: marshal | password: 123456
client1._client_id = "123dde";
client1.on_connect = on_connect
client1.on_message = on_message
HOST = "127.0.0.1" #IP address of broker
client1.connect_async(HOST)
client1.loop_start() #client1 runs a thread at background
for i in range(100):
client1.subscribe('manipulated') #client1 subcribes a topic 'manipulated'
client1.publish('position',i) #client1 publishes topic 'position' with content 'i'
time.sleep(1)
client1.loop_stop()
print("end")
python工程
3.运行效果
net服务端
net客户端
python客户端
net服务端+net客户端+python客户端 之间的通讯