客户端:
# encoding: utf-8
import paho.mqtt.client as mqtt
import sys
ThemControl = "mq主题"
# print(ThemControl)
print(ThemControl)
#要发送的mq消息
data = "1,1"
HOST = "mq服务器地址"
PORT = 端口号
def test():
client = mqtt.Client()
client.connect(HOST, PORT, 60)
client.publish(ThemControl,data,2)
# client.loop_forever()
if __name__ == '__main__':
test()
服务端:
#-*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import os
import time
import sys
ThemControl = "mq主题"
def on_connect(client, userdata, flags, rc):
client.subscribe(ThemControl)
# print("Connected with result code "+str(rc))
def on_message(client, userdata, msg):
print(msg.topic+" " + ":" + str(msg.payload))
# client.loop_forever()
def main():
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mq服务器地址", 端口号, 60)
while data:
client.loop()
if __name__== '__main__':
main()
注意:服务端监听的主题和客户端推送的主题必须是同一个主题。
网友评论