Python mqtt分布式框架搭建

订阅消息
#!/usr/bin/python

-- coding:utf-8 --

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))

def on_message(client, userdata, msg):
# print(msg.topic + " " + str(msg.payload))
mes = msg.payload
print mes

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.on_disconnect = on_disconnect

client.connect(‘127.0.0.1’, 1883, 600) # 600为keepalive的时间间隔
client.subscribe(‘A’, qos=0)
client.loop_forever() # 保持连接

推送消息
#!/usr/bin/python

-- coding:utf-8 --

import paho.mqtt.client as mqtt
import os

def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))

def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))

def publish(ip, post, live_time, name, info):
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(ip, post, live_time) # 600为keepalive的时间间隔
client.publish(name, payload=str(info), qos=0)

if name == ‘main’:
ip1 = '127.0.0.1"
post1 = 1883
live_time1 = 600
name1 = ‘A’
info1 = os.getenv(‘PARAMS’)
publish(ip1, post1, live_time1, name1, info1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值