MQTT Introduction and Go code implementation

Source: Internet
Author: User

The MQTT (message Queuing Telemetry Transport, the Messaging Queue Telemetry Transport protocol) is a "lightweight" communication protocol based on the Publish/subscribe (Publish/subscribe) pattern, which is built on the TCP/IP protocol. Released by IBM in 1999. The biggest advantage of MQTT is the ability to provide real-time, reliable messaging services to connected remote devices with minimal code and limited bandwidth. As a low-overhead, low-bandwidth-occupied Instant Messaging protocol, it has a wide range of applications in the IoT, small devices, mobile applications, and more.
MQTT is a client-server-based message publishing/subscription transport protocol. The MQTT protocol is lightweight, simple, open, and easy to implement, and these features make it a very wide range of applications. In many cases, including restricted environments, such as machine-to-machine (ATM) communications and the Internet of Things (IoT). It is widely used in satellite link communication sensors, occasional dial-up medical devices, smart homes, and some miniaturized devices.
The implementation of the MQTT protocol requires client and server-side communication, and in the process of communication, there are three identities in the MQTT protocol: publisher (Publish), Agent (Broker) (server), Subscriber (Subscribe). Where the Publisher and subscriber of the message are clients, the message agent is the server, and the message Publisher can be both subscribers.

The messages that MQTT transmits are divided into two parts: subject (Topic) and load (payload):

(1) Topic, can be understood as the type of message, Subscriber Subscription (Subscribe), you will receive the message content of the topic (payload);

(2) payload, which can be understood as the content of the message, refers to what the Subscriber specifically wants to use.
2 Network transmission and application messages
MQTT constructs the underlying network transport: it establishes a client-to-server connection, providing an ordered, lossless, byte-stream-based bidirectional transmission between the two.

When application data is sent over an MQTT network, MQTT relates the quality of service (QoS) and subject name (TOPIC) associated with it.

3 MQTT Client

An application or device that uses the MQTT protocol, which always establishes a network connection to the server. Clients can:

(1) Publishing information that may be subscribed by other clients;

(2) Subscribing to other client-issued messages;

(3) Unsubscribe or delete the message of the application;

(4) Disconnect from the server.

4 MQTT Server
An MQTT server is called a message agent (broker) and can be an application or a device. It is located between the message Publisher and the Subscriber, and it can:

(1) Accept the network connection from the customer;

(2) Receiving application information issued by customers;

(3) Processing of subscriptions and unsubscribe requests from clients;

(4) Forward the application message to the subscribed customer.

5 subscriptions, topics, sessions in the MQTT protocol
First, Subscription (Subscription)

The subscription contains the subject filter (Topic filter) and the maximum quality of service (QoS). The subscription is associated with a session. A session can contain multiple subscriptions. Each subscription in each session has a different subject filter.

Ii. Sessions (session)

After each client is connected to the server, it is a session where there is a state interaction between the client and the server. A session exists between a network, or it may span multiple contiguous network connections between the client and the server.

Third, subject name (Topic name)

A label that connects to an application message that matches the server's subscription. The server sends the message to each client that subscribes to the matching label.

Iv. Theme Filters (Topic filter)

A wildcard filter on the subject name, used in the subscription expression, that represents the multiple topics to which the subscription matches.

V. Load (Payload)

Content that is specifically received by the message Subscriber.

Testing the MQTT Client
Mqttbox-win

Go code
https://www.eclipse.org/paho/...

Package Main

Import (
"FMT"
Import the Paho Go MQTT Library
MQTT "Github.com/eclipse/paho.mqtt.golang"
"OS"
"Time"
)

Define a function for the default message handler
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 () {
Create a clientoptions struct setting the broker address, ClientID, turn
Off trace output and set the default message handler
OPTs: = MQTT. Newclientoptions (). Addbroker ("tcp://iot.eclipse.org:1883")
OPTs. Setclientid ("Go-simple")
OPTs. Setdefaultpublishhandler (f)

Create and start a client using the above clientoptions
c: = MQTT. Newclient (opts)
If token: = C.connect (); Token. Wait () && token. Error ()! = Nil {

panic(token.Error())

}

Subscribe to the Topic/go-mqtt/sample and request messages to be delivered
At a maximum QoS of zero, wait for the receipt to confirm the subscription
If token: = C.subscribe ("Go-mqtt/sample", 0, Nil); Token. Wait () && token. Error ()! = Nil {

fmt.Println(token.Error())os.Exit(1)

}

Publish 5 Messages To/go-mqtt/sample at QoS 1 and wait for the receipt
From the server after sending each message
For I: = 0; I < 5; i++ {

text := fmt.Sprintf("this is msg #%d!", i)token := c.Publish("go-mqtt/sample", 0, false, text)token.Wait()

}

Time. Sleep (3 * time. Second)

Unsubscribe From/go-mqtt/sample
If token: = C.unsubscribe ("Go-mqtt/sample"); Token. Wait () && token. Error ()! = Nil {

fmt.Println(token.Error())os.Exit(1)

}

C.disconnect (250)
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.