In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces how to use MQTT in Golang, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Golang is a statically strongly typed, compiled, parallel programming language developed by Google with garbage collection function. Go is expressive, concise, clean and efficient. Its concurrency mechanism enables it to write programs easily so as to maximize the use of multi-core and network machines, while its novel type system can achieve flexible and modular program construction. Go compiles into machine code quickly, but it also has the convenience of garbage collection and the powerful function of runtime reflection. It is a fast, statically typed, compiled language, just like a dynamically typed, interpreted language.
MQTT is a lightweight Internet of things message transmission protocol based on publish / subscribe mode, which can provide real-time and reliable message service for networking devices with very little code and bandwidth. it is widely used in Internet of things, mobile Internet, intelligent hardware, vehicle Internet, power energy and other industries.
This paper mainly introduces how to use paho.mqtt.golang client library in Golang project to realize the functions of connecting, subscribing, sending and receiving messages between client and MQTT server.
Project initialization
This project is developed and tested based on go1.13.12.
Go versiongo version go1.13.12 darwin/amd64
This project uses paho.mqtt.golang as the MQTT client library to install:
Go get github.com/eclipse/paho.mqtt.golangGo MQTT usage
This article will use the free public MQTT server provided by EMQ X, which is based on EMQ X's MQTT Internet of things cloud platform. The server access information is as follows:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
Connect to the MQTT server package mainimport ("fmt" mqtt "github.com/eclipse/paho.mqtt.golang"time") var messagePubHandler mqtt.MessageHandler = func (client mqtt.Client, msg mqtt.Message) {fmt.Printf ("Received message:% s from topic:% s\ n", msg.Payload () Msg.Topic ()} var connectHandler mqtt.OnConnectHandler = func (client mqtt.Client) {fmt.Println ("Connected")} var connectLostHandler mqtt.ConnectionLostHandler = func (client mqtt.Client, err error) {fmt.Printf ("Connect lost:% v") Err)} func main () {var broker = "broker.emqx.io" var port = 1883 opts: = mqtt.NewClientOptions () opts.AddBroker (fmt.Sprintf ("tcp://%s:%d", broker) Port) opts.SetClientID ("go_mqtt_client") opts.SetUsername ("emqx") opts.SetPassword ("public") opts.SetDefaultPublishHandler (messagePubHandler) opts.OnConnect = connectHandler opts.OnConnectionLost = connectLostHandler client: = mqtt.NewClient (opts) if token: = client.Connect () Token.Wait () & & token.Error ()! = nil {panic (token.Error ())}}
ClientOptions: used to set options such as broker, port, client id, user name and password
MessagePubHandler: global MQTT pub message processing
ConnectHandler: callback of connection
ConnectLostHandler: callback of lost connection
If you want to use TLS connection, you can set it as follows:
Func NewTlsConfig () * tls.Config {certpool: = x509.NewCertPool () ca, err: = ioutil.ReadFile ("ca.pem") if err! = nil {log.Fatalln (err.Error ())} certpool.AppendCertsFromPEM (ca) / / Import client certificate/key pair clientKeyPair, err: = tls.LoadX509KeyPair ("client-crt.pem") "client-key.pem") if err! = nil {panic (err)} return & tls.Config {RootCAs: certpool, ClientAuth: tls.NoClientCert, ClientCAs: nil, InsecureSkipVerify: true, Certificates: [] tls.Certificate {clientKeyPair},}
If you do not set the client certificate, you can set it as follows:
Func NewTlsConfig () * tls.Config {certpool: = x509.NewCertPool () ca, err: = ioutil.ReadFile ("ca.pem") if err! = nil {log.Fatalln (err.Error ())} certpool.AppendCertsFromPEM (ca) return & tls.Config {RootCAs: certpool,}
Then set up TLS
Var broker = "broker.emqx.io" var port = 8883opts: = mqtt.NewClientOptions () opts.AddBroker (fmt.Sprintf ("tcp://%s:%d", broker, port)) tlsConfig: = NewTlsConfig () opts.SetTLSConfig (tlsConfig) / / other options subscribe to func sub (client mqtt.Client) {topic: = "topic/test" token: = client.Subscribe (topic, 1, nil) token.Wait () fmt.Printf ("Subscribed to topic% s" Topic)} publish message func publish (client mqtt.Client) {num: = 10 for I: = 0 I
< num; i++ { text := fmt.Sprintf("Message %d", i) token := client.Publish("topic/test", 0, false, text) token.Wait() time.Sleep(time.Second) }}测试 我们使用以下代码进行测试 package mainimport ( "fmt" mqtt "github.com/eclipse/paho.mqtt.golang" "log" "time")var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())}var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) { fmt.Println("Connected")}var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) { fmt.Printf("Connect lost: %v", err)}func main() { var broker = "broker.emqx.io" var port = 1883 opts := mqtt.NewClientOptions() opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port)) opts.SetClientID("go_mqtt_client") opts.SetUsername("emqx") opts.SetPassword("public") opts.SetDefaultPublishHandler(messagePubHandler) opts.OnConnect = connectHandler opts.OnConnectionLost = connectLostHandler client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } sub(client) publish(client) client.Disconnect(250)}func publish(client mqtt.Client) { num := 10 for i := 0; i < num; i++ { text := fmt.Sprintf("Message %d", i) token := client.Publish("topic/test", 0, false, text) token.Wait() time.Sleep(time.Second) }}func sub(client mqtt.Client) { topic := "topic/test" token := client.Subscribe(topic, 1, nil) token.Wait() fmt.Printf("Subscribed to topic: %s", topic)} 运行代码,可以看到 MQTT 连接、订阅成功,并能成功收到订阅 topic 的消息On how to use MQTT in Golang to share here, I hope the above content can be of some help to you, can 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.