python-MQTT双向传输数据

嫖来的百度云服务的做法:生成一个服务端推送、客户端订阅的话题,同时生成一个服务端订阅、客户端推送的话题;注意权限问题

示例代码

  1. 服务端
import json
import time
import paho.mqtt.client as mqtt
from threading import Thread

address = "127.0.0.1"
port = 1883


def pub():
    client = mqtt.Client()

    client.on_connect = lambda client, userdata, flags, rc: print(
        "Connected with result code: " + str(rc))
    client.on_message = lambda client, userdata, msg: print(
        msg.topic + " " + str(msg.payload))
    client.connect(address, port, 60)
    client.loop_start()
    while True:
        client.publish('Publish', payload="Server", qos=0)
        time.sleep(1)


def sub():
    client = mqtt.Client()
    client.on_connect = lambda client, userdata, flags, rc: print(
        "Connected with result code: " + str(rc))
    client.on_message = lambda client, userdata, msg: print(
        msg.topic + " " + str(msg.payload))
    client.connect(address, port, 60)
    client.subscribe('Upload', qos=0)
    client.loop_forever()


downData = Thread(target=pub)
rev = Thread(target=sub)
downData.start()
rev.start()

  1. 客户端
import paho.mqtt.client as mqtt
import time
import json
from threading import Thread

address = "127.0.0.1"
port = 1883


def updataData():
    client = mqtt.Client()
    client.on_connect = lambda client, userdata, flags, rc: print(
        "Connected with result code: " + str(rc))
    client.on_message = lambda client, userdata, msg: print(
        msg.topic + " " + str(msg.payload))
    client.connect(address, port, 60)
    client.loop_start()
    while True:
        client.publish('Upload', payload=json.dumps({
     "msg":"upload"}), qos=0)
        time.sleep(1)


def downData():
    client = mqtt.Client()
    client.on_connect = lambda client, userdata, flags, rc: print(
        "Connected with result code: " + str(rc))
    client.on_message = lambda client, userdata, msg: print(
        msg.topic + " " + str(msg.payload))
    client.connect(address, port, 60)
    client.subscribe('Publish', qos=0)
    client.loop_forever()


update = Thread(target=updataData)
down = Thread(target=downData)
update.start()
down.start()

你可能感兴趣的:(Python,mqtt,python)