Build an MQTT-broker server on windows and use python to simply test the use of publish and subscribe messages

**

Introduction

**
MQTT (Message Queuing Telemetry Transport) is an instant messaging protocol developed by IBM. It is more suitable for remote sensor and control device communications on low-bandwidth, unreliable networks. It is increasingly becoming the Internet of Things An important part of the communication protocol. MQTT is now mainly used for instant messaging, Internet of Things M2M, Internet of Things collection, etc. This article gives a detailed introduction to the construction of common open source MQTT servers in the community on common operating systems. At present, some open source MQTT service middleware are:

  • 1) EMQX : github 6.3k stars (download link for installation-free version: https://www.emqx.io/downloads/broker/v4.1.0/ )
  • 2)Mosquitto:github 3.9k stars
  • 3) Apollo : An upgraded version of ActiveMQ, github 138 stars, but the project has not been updated for 3 to 4 years. The old version of ActiveMQ, which it claims, is updated more frequently.

EMQ server is built on Windows

EMQ (Erlang/Enterprise/Elastic MQTT Broker) is an open source IoT MQTT message server developed based on the Erlang/OTP platform. Erlang/OTP is an excellent Soft-Realtime, Low-Latency, and Distributed language platform. Generally speaking, the MQTT service in the production environment is recommended to be built on the Linux operating system, but as a verification and use stage for you, it can be built, run and tested on the common Windows platform.
**

installation steps

**

  • 1) Click here to download the EMQ windows version
  • 2) Unzip emqttd-windows7-v2.3.9.zip (here is unzip to D drive)
  • 3) Open the Windows command line window, and enter the directory of the decompression emqx\bin
  • 4) Start EMQ in the Windows command line and execute the following commandsemqx.cmd start
    Insert picture description here
  • 5) EMQ provides a back-end web console through which users can
    view the server running status, statistical data, client, session, topic, subscription, plug-in ( Plugin). If EMQ is installed on this machine, open http://127.0.0.1:18083*** in the browser , enter the default user name "admin" and the default password "public" * to enter the EMQ management console. As shown in the figure below, in the "Stats(1)" table, some basic information about the client and topic are displayed. For example, the number of "Clients/Count" is 0, which means that the number of currently connected clients is 0; "Client/ Max" indicates the maximum value that the connection has ever reached, etc. I will not introduce each item one by one here. After the reader is familiar with the MQTT protocol, he can understand the content on the monitoring dashboard.
    (The web browser can access the following interface to indicate that the installation is successful)
    Insert picture description here

The following uses python to test publishing and subscribing to messages:

First, you need to install the mqtt module:pip install paho-mqtt

Publish client code 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)

Subscription client code 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() # 保持连接

===========================================================================

In another test method, after publishing is used, the subscriber keeps a long connection to monitor the messages of the publisher, which is actually the same as the above.

# -*- 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()

Topic information after successful connection
Insert picture description here
done, thanks!

Guess you like

Origin blog.csdn.net/qq_43030934/article/details/107638059