iOS development uses the MQTT protocol for remote communication

Source: Internet
Author: User

I. Introduction of the agreement:

1. MQTT (msg Queuing Telemetry Transport, Message Queuing telemetry transmission) is an Instant Messaging protocol developed by IBM that is likely to be an important part of the Internet of things. The protocol supports all platforms, almost all networked items and externally connected, and is used as sensors and actuators.

Second, the characteristics of the Agreement:

1.MQTT is a protocol designed to communicate with a wide range of remote sensors and embedded control devices that have limited computational power and are working in low bandwidth, unreliable networks, with the following key features:

1, using the Publish/Subscribe message pattern, providing a one-to-many message release, decoupling the application;

2, the message transmission of the content of the load shielding;

3, the use of TCP/IP to provide network connectivity;

4 ", there are three kinds of message QoS release service quality;

A, "at most one time", message publishing relies entirely on the underlying TCP/IP network. Message loss or repetition occurs. This level can be used when the environment sensor data, loss of a read record does not matter, because there will be a second time to send.

B, "at least once" to ensure that the message arrives, but the message duplication may occur.

C, "only once" to ensure that the message arrives once. This level can be used for situations where, in a billing system, duplicate or missing messages can result in incorrect results.

5, small transmission, using very small (fixed-length head is 2 bytes), protocol switching minimized to reduce network traffic;

6. Use the last would and Testament features to notify the client of the mechanism of abnormal interrupts on the parties.

Third, the Protocol application scenario:

1. mobile messaging, Internet of things, car networking, smart hardware and even energy exploration

2. design mode support: 1 byte header, 2 byte heartbeat, message QoS

Iv. Integration of iOS client steps using the MQTT protocol :

1,GitHub search for data mqtt and download, there will be two (recommended to use a second):

A, Mqttkit: Stop update : Https://github.com/mobile-web-messaging/MQTTKit

B, Mqttclient: Regular update : Https://github.com/novastone-media/MQTT-Client-Framework

2, import Mqtt and Socketrocket two frame to the project, if encountered the compilation error "_utf8_nextcharsafebody", referenced from:, remember to add system dependent library LIBICUCORE.TBD

3. Create a transport type

Mqttcfsockettransport* transport=[[mqttcfsockettransport alloc]init];

Transport. host[email protected] "192.168.1.1";

Transport. port=[@ "8080" intvalue];

4. Create a session task and set up a proxy

Mqttsession* session=[[mqttsession alloc]init];

Session. delegate= self;

Session. Transport=transport;

Session. username=@ "Peter";

Session. password=@ "123456";

5. Subscribe to the theme

BOOL issucess = [Session Connectandwaittimeout: +]; Connecting sessions, setting time-outs

if (issucess) {

[Session Subscribetotopic:nil atlevel:mqttqoslevelatmostonce subscribehandler:^ ( Nserror *error, nsarray<nsnumber *> *gqoss) {

if (error) {

NSLog (@ "Connection failed:%@", error. ) localizeddescription);

}else{

NSLog (@ "Connection succeeded:%@", Gqoss);

}

}];

}

5. KVO Monitoring Status

[self. Session Addobserver:self forkeypath:@ "ststus" options: Nskeyvalueobservingoptionold context:nil];

-(void) Observevalueforkeypath: (nsstring *) keypath ofobject: (ID) object change: (nsdictionary< Nskeyvaluechangekey,id> *) Change context: (void *) context{

Disconnecting connection

if (self. Session. Status==mqttsessionstatusdisconnecting) {

[Self. session Connect]; //re-connect

}

}

6. Send data

-(void) Sending: (Mqttsession *) session type: (mqttcommandtype) type QoS: (mqttqoslevel) QoS retained: ( bool) retained duped: (bool) duped Mid: (UInt16) Mid data: (NSData *) data{

[Session Publishandwaitdata:d ATA

ontopic:@ "topic"

retain:NO

QoS:mqttqoslevelatleastonce];

}

7. Receive data

-(void) Newmessage: (mqttsession *) session data: (NSData *) data ontopic: (nsstring *) Topic QoS: ( Mqttqoslevel) QoS retained: (BOOL) retained mid: (unsigned int) mid{

nsdictionary* dict=[nsjsonserialization jsonobjectwithdata:d ata options: Nsjsonreadingmutablecontainers error:nil];

Self . datadict=dict; //Save Global Properties

if ([topic rangeofstring:@ "Device_control"]. location!=nsnotfound) {

//Control equipment

}

}

8. Disconnection of Service Connection

-(void) connectionclosed: (mqttsession *) session{

[Session Disconnect]; //Disconnect

[Session Close]; //Off

}

9. Cancellation of subscription Service

-(void) unsubackreceived: (mqttsession *) session MsgID: (UInt16) msgid{

[Session Unsubscribetopic:@ "topic" unsubscribehandler: ^ (nserror *error) {

}];

}

iOS development uses the MQTT protocol for remote communication

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.