**
**
MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,它比较适合于在低带宽、不可靠的网络的进行远程传感器和控制设备通讯等,正在日益成为物联网通信协议的重要组成部分。MQTT现在主要用于即时通讯,物联网M2M,物联网采集等。本文就社区上常见的开源MQTT服务器在常见操作系统上的搭建做详细介绍。目前一些开源MQTT服务中间件有:
EMQ (Erlang/Enterprise/Elastic MQTT Broker) 是基于 Erlang/OTP 平台开发的开源物联网 MQTT 消息服务器。Erlang/OTP 是出色的软实时(Soft-Realtime)、低延时(Low-Latency)、分布式(Distributed) 的语言平台。一般来说,生产环境的MQTT服务建议搭建在Linux操作系统上,但是作为在给你验证和使用阶段,可以在常见的Windows平台上搭建、运行和测试。
**
**
emqx.cmd start
首先需要安装mqtt模块:pip install paho-mqtt
发布客户端代码pub.py
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))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883, 600) # 600为keepalive的时间间隔
client.publish('fifa', payload='amazing', qos=0)
订阅客户端代码sub.py
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))
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('fifa', qos=0)
client.loop_forever() # 保持连接
===========================================================================
另外一种测试方式,使用发布之后,订阅端保持长连接监听发布端消息,和上面其实是一样的。
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
import time
HOST = "127.0.0.1"
PORT = 1883
# client_id = "" # 没有就不写,此处部分内容用xxx代替原内容,下同
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("data/receive") # 订阅消息
def on_message(client, userdata, msg):
print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))
def on_subscribe(client, userdata, mid, granted_qos):
print("On Subscribed: qos = %d" % granted_qos)
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection %s" % rc)
data = {
"type":2,
"timestamp": time.time(),
"messageId":"9fcda359-89f5-4933-xxxx",
"command":"xx/recommend",
"data":{
"openId":"xxxx",
"appId":'xxxx',
"recommendType":"temRecommend"
}
}
param = json.dumps(data)
client = mqtt.Client()
client.username_pw_set("user")
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
client.connect(HOST, PORT, 60)
client.publish("data/send", payload=param, qos=0) # 发送消息
client.loop_forever()