In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the sample analysis of commonly used MQTT clients, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Preface
MQTT is a lightweight publish-subscribe mode message transport protocol designed specifically for Internet of things applications with low bandwidth and unstable network environment. MQTT is based on publish / subscribe paradigm and works on TCP/IP protocol family. MQTT protocol is lightweight, simple, open and easy to implement, which makes it applicable to a wide range of applications.
MQTT is based on the client-server communication mode, and the MQTT server is called MQTT Broker. At present, there are many MQTT Broker options in the industry, and the advantages and disadvantages and functional differences will not be discussed in this article. This paper takes EMQ X, the most popular MQTT message server in the open source community, as an example, using the public Broker broker.emqx.io provided by EMQ, through a simple client to connect to Broker and publish and process messages, collates and summarizes the usage and samples of MQTT client libraries under different programming languages and platforms.
Introduction to sample application
The behavior of the MQTT client throughout the lifecycle can be summarized as: establishing a connection, subscribing to a topic, receiving and processing messages, publishing messages to a specified topic, unsubscribing, and disconnecting.
Standard client libraries expose corresponding methods in each link, and the meaning of method parameters required by different libraries in the same link is roughly the same. Which parameters are selected and which features are enabled require users to have an in-depth understanding of MQTT protocol features and combined with the actual application scenario.
Taking a client connecting, publishing and processing messages as an example, the parameters that need to be used in each link are given:
Establish a connection:
Specify MQTT Broker basic information access address and port
Specify whether the transport type is TCP or MQTT over WebSocket
If you enable TLS, you need to select the protocol version and carry the corresponding certificate.
If authentication and authentication is enabled in Broker, the client needs to carry the corresponding MQTT Username Password information.
Configure client parameters such as keepalive duration, clean session reply reservation flag bit, MQTT protocol version, testamentary message (LWT), etc.
Subscription topic: you can subscribe to a topic after a successful connection is established. You need to specify topic information.
Specify the topic filter Topic, which supports the use of topic wildcards + and # when subscribing
Specify QoS. Qos 012 is optional according to the implementation of client library and Broker. Note that some Broker and cloud service providers do not support some QoS levels, such as AWS IoT, Aliyun IoT suite, and Azure IoT Hub do not support QoS 2 level messages.
Subscription to topics may fail due to network problems and restrictions of ACL rules on the Broker side
Receive messages and process:
Generally, the processing function is specified when connecting, and the processing method is slightly different according to the network programming model of the client library and the platform.
Publish message: publish a message to a specified topic
Specify the target topic. Note that the topic cannot contain wildcards + or #. If the topic contains wildcards, it may lead to message publishing failure, client disconnection, etc. (depending on how Broker is implemented with the client library)
Specify the QoS level of the message. There are also different Broker and different QoS levels supported by the platform. For example, if Azure IoT Hub publishes QoS 2 messages, the client will be disconnected.
Specifies the message body content, which cannot exceed the maximum message size set by Broker
Specifies that the message Retain retains message flag bits
Unsubscribe:
Just specify the target theme.
Disconnect:
Actively disconnect and will issue a testamentary message (LWT)
Eclipse Paho C and Eclipse Paho Embedded C
Both Eclipse Paho C and Eclipse Paho Embedded C are client libraries under the Eclipse Paho project, and both are fully functional MQTT clients written in ANSI C. Eclipse Paho Embedded C can be used on desktop operating systems, but mainly for embedded environments such as mbed,Arduino and FreeRTOS.
The client has synchronous / asynchronous API, starting with MQTTClient and MQTTAsync:
Synchronous API is designed to be simpler and more useful, and some calls will block until the operation is complete, making it easier to use programmatically
There is only one call block API-waitForCompletion in asynchronous API, which notifies the result through callback, which is more suitable for non-main thread environments.
For more information on downloading and using the two libraries, please go to the project home page. This article uses Eclipse Paho C, and the sample code is provided as follows:
# include "stdio.h" # include "stdlib.h" # include "string.h" # include "MQTTClient.h" # define ADDRESS "tcp://broker.emqx.io:1883" # define CLIENTID "emqx_test" # define TOPIC "testtopic/1" # define PAYLOAD "Hello World!" # define QOS 1#define TIMEOUT 10000Lint main (int argc, char* argv []) {MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc; MQTTClient_create (& client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); / / Connection parameters conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; if ((rc = MQTTClient_connect (client, & conn_opts)! = MQTTCLIENT_SUCCESS) {printf ("Failed to connect, return code% dn", rc) Exit (- 1);} / / Publish message pubmsg.payload = PAYLOAD; pubmsg.payloadlen = strlen (PAYLOAD); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage (client, TOPIC, & pubmsg, & token) Printf ("Waiting for up to% d seconds for publication of% sn"on topic% s for client with ClientID:% sn", (int) (TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID); rc = MQTTClient_waitForCompletion (client, token, TIMEOUT); printf ("Message with delivery token% d deliveredn", token); / / Disconnect MQTTClient_disconnect (client, 10000); MQTTClient_destroy (& client); return rc;} Eclipse Paho Java Client
Eclipse Paho Java Client is a MQTT client library written in Java that can be used with JVM or other Java-compatible platforms such as Android.
Eclipse Paho Java Client provides MqttAsyncClient and MqttClient asynchronous and synchronous API.
Install via Maven:
Org.eclipse.paho org.eclipse.paho.client.mqttv3 1.2.2
The sample code for the connection is as follows:
App.java
Package io.emqx;import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttConnectOptions;import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttMessage;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class App {public static void main (String [] args) {String subTopic = "testtopic/#"; String pubTopic = "testtopic/1"; String content = "Hello World" Int qos = 2; String broker = "tcp://broker.emqx.io:1883"; String clientId = "emqx_test"; MemoryPersistence persistence = new MemoryPersistence (); try {MqttClient client = new MqttClient (broker, clientId, persistence); / / Connection options MqttConnectOptions connOpts = new MqttConnectOptions (); connOpts.setUserName ("emqx_test") ConnOpts.setPassword ("emqx_test_password" .toCharArray ()); / / Retain connection connOpts.setCleanSession (true); / / Set callback client.setCallback (new PushCallback ()); / / Setup connection System.out.println ("Connecting to broker:" + broker); client.connect (connOpts); System.out.println ("Connected") System.out.println ("Publishing message:" + content); / / Publish client.subscribe (subTopic); / / Required parameters for publishing message MqttMessage message = new MqttMessage (content.getBytes ()); message.setQos (qos); client.publish (pubTopic, message); System.out.println ("Message published"); client.disconnect () System.out.println ("Disconnected"); client.close (); System.exit (0);} catch (MqttException me) {System.out.println ("reason" + me.getReasonCode ()); System.out.println ("msg" + me.getMessage ()); System.out.println ("loc" + me.getLocalizedMessage ()) System.out.println ("cause" + me.getCause ()); System.out.println ("excep" + me); me.printStackTrace ();}}
Callback message handling class OnMessageCallback.java
Package io.emqx;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;import org.eclipse.paho.client.mqttv3.MqttCallback;import org.eclipse.paho.client.mqttv3.MqttMessage;public class OnMessageCallback implements MqttCallback {public void connectionLost (Throwable cause) {/ / Reconnect after lost connection. System.out.println ("Connection lost, and re-connect here.");} public void messageArrived (String topic, MqttMessage message) throws Exception {/ / Message handler after receiving message System.out.println ("Topic:" + topic); System.out.println ("QoS:" + message.getQos ()); System.out.println ("Payload:" + new String (message.getPayload () } public void deliveryComplete (IMqttDeliveryToken token) {System.out.println ("deliveryComplete-" + token.isComplete ());}} Eclipse Paho MQTT Go client
Eclipse Paho MQTT Go Client is the Go language version client library under the Eclipse Paho project, which can connect to MQTT Broker to publish messages, subscribe to topics and receive published messages, and support a fully asynchronous mode of operation.
The client relies on Google's proxy and websockets packages and completes the installation with the following command:
Go get github.com/eclipse/paho.mqtt.golang
The sample code for the connection is as follows:
Package mainimport ("fmt"log"os"time"github.com/eclipse/paho.mqtt.golang") var f mqtt.MessageHandler = func (client mqtt.Client, msg mqtt.Message) {fmt.Printf ("TOPIC:% sn", msg.Topic ()) fmt.Printf ("MSG:% sn" Msg.Payload ()} func main () {mqtt.DEBUG = log.New (os.Stdout, ", 0) mqtt.ERROR = log.New (os.Stdout,") 0) opts: = mqtt.NewClientOptions (). AddBroker ("tcp://broker.emqx.io:1883"). SetClientID ("emqx_test_client") opts.SetKeepAlive (60 * time.Second) / / Message callback handler opts.SetDefaultPublishHandler (f) opts.SetPingTimeout (1 * time.Second) c: = mqtt.NewClient (opts) if token: = c.Connect () Token.Wait () & & token.Error ()! = nil {panic (token.Error ())} / / Subscription if token: = c.Subscribe ("testtopic/#", 0, nil) Token.Wait () & & token.Error ()! = nil {fmt.Println (token.Error ()) os.Exit (1)} / / Publish message token: = c.Publish ("testtopic/1", 0, false "Hello World") token.Wait () time.Sleep (6 * time.Second) / / Cancel subscription if token: = c.Unsubscribe ("testtopic/#") Token.Wait () & & token.Error ()! = nil {fmt.Println (token.Error ()) os.Exit (1)} / / Disconnect c.Disconnect (250) time.Sleep (1 * time.Second)} emqtt: Erlang MQTT client library provided by EMQ
Emqtt is a client library provided by the official EMQ of open source MQTT Broker EMQ X, which is suitable for the Erlang language.
Erlang Ecology has multiple MQTT Broker implementations, such as RabbitMQ, VerenMQ, EMQ X, etc. that support MQTT through plug-ins. However, there is little choice for MQTT client libraries, and emqtt is the best choice among the Erlang client libraries included in the MQTT community.
Emqtt is implemented entirely by Erlang, supporting MQTT v3.1.1 and MQTT v5.0 protocol versions, supporting SSL one-and-two-way authentication and WebSocket connection. Another MQTT benchmark tool, emqtt_bench, is built on this client library.
Emqtt is used as follows:
ClientId =. {ok, ConnPid} = emqtt:start_link ([{clientid, ClientId}]). {ok, _ Props} = emqtt:connect (ConnPid). Topic = .QoS = 1. {ok, _ Props, _ ReasonCodes} = emqtt:subscribe (ConnPid, {Topic, QoS}). {ok, _ PktId} = emqtt:publish (ConnPid, QoS).% If the qos of publish packet is 0, `publish` function would not return packetid.ok = emqtt:publish (ConnPid, ConnPid, 0).% Recursively get messages from mail box.Y = fun (Proc)-> ((fun (F)-> F (F) end) ((fun (ProcGen)-> Proc (fun ()-> (ProcGen (ProcGen)) () end) end) end.Rec = fun (Receive)-> fun ()-> receive {publish, Msg}-> io:format ("Msg: ~ pairn", [Msg]), Receive () _ Other-> Receive () after 5-> ok end end end. (y (Rec)) ().% If you don't like y combinator, you can also try named function to recursively get messages in erlang shell.Receive = fun Rec ()-> receive {publish, Msg}-> io:format ("Msg: ~ pairn", [Msg]), Rec () _ Other-> Rec () after 5-> ok end end.Receive (). {ok, _ Props, _ ReasonCode} = emqtt:unsubscribe (ConnPid,). Ok = emqtt:disconnect (ConnPid). MQTT.js Web side & Node.js platform MQTT client
MQTT.js is a module written by JavaScript that implements the client function of MQTT protocol and can be used in Node.js or browser environment. When used in Node.js, you can either use the-g global installation as a command line or integrate it into a project.
Due to the single-thread feature of JavaScript, MQTT.js is a fully asynchronous MQTT client. MQTT.js supports MQTT and MQTT over WebSocket. The degree of support in different running environments is as follows:
Browser environment: MQTT over WebSocket (including custom browser environments such as WeChat Mini Programs, Alipay Mini Program, etc.)
Node.js environment: MQTT, MQTT over WebSocket
The API is the same in different environments except for a small number of connection parameters.
Install using npm:
Npm i mqtt
Install using CDN (browser):
/ / Initialize a global mqtt variable console.log (mqtt)
Sample code:
/ / const mqtt = require ('mqtt') import mqtt from' mqtt'// Connection optionconst options = {clean: true, / / Retain connection connectTimeout: 4000, / / Timeout / / Authtication clientId: 'emqx_test', username:' emqx_test', password: 'emqx_test' } / / Connection string// ws: unsecured WebSocket// wss: secured WebSocket connection// mqtt: unsecured TCP connection// mqtts: secured TCP connectionconst connectUrl = 'wss://broker.emqx.io:8084/mqtt'const client = mqtt.connect (connectUrl, options) client.on (' reconnect', (error) = > {console.log ('reconnect:', error)}) client.on (' reconnect', (error) = > {console.log ('reconnect:', error)}) client.on (' message', (topic) Message) = > {console.log ('message:', topic, message.toString ())}) Eclipse Paho Python
Eclipse Paho Python is the Python language client library under the Eclipse Paho project, which can connect to MQTT Broker to publish messages, subscribe to topics, and receive published messages.
Install using the PyPi package management tool:
Pip install paho-mqtt
Code sample:
Import paho.mqtt.client as mqtt# Successful Connection Callbackdef on_connect (client, userdata, flags, rc): print ('Connected with result code' + str (rc)) client.subscribe ('testtopic/#') # Message delivery callbackdef on_message (client, userdata, msg): print (msg.topic+ "+ str (msg.payload) client = mqtt.Client () # Set callback handlerclient.on_connect = on_connectclient.on_message = on_message# Set up connectionclient.connect (' broker.emqx.io', 1883) 60) # Publish messageclient.publish ('emqtt',payload='Hello World',qos=0) client.loop_forever () sample analysis of commonly used MQTT clients is shared here I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.