(C) Based on the client's message push mqtt

About MQTT

mqtt architecture based on subscriber model, the client communicate with each other if under, you must subscribe to the same theme, that have subscribed to the same topic, there is no way to communicate between the client directly. Subscription model obvious benefit is then only need to post messages to bulk topic, all subscribed to the topic of the client can receive the news.

Send a message must be sent to a topic, important to note that regardless of whether the client subscribed to the topic can send a message to the topic, as well as if the client subscribed to the topic, the message will be sent by itself is received.

Also important to note that the QoS, which represents the message transmission mode, QoS follows:

  • 0 stands for "at most once", the news release completely dependent on the underlying TCP / IP network. Occur missing or duplicate messages. This level can be used in the following cases, the environmental sensor data, loss of a read record does not matter, because there will be sent a second time soon after.
  • 1 stands for "at least once" to ensure that the message reaches, but the message is repeated may occur.
  • 2 represents the "only once" to ensure that the message reaches once. This level may be used in the following case, the charging system, the message is repeated or missing leads to incorrect results. Note: Due to the server using Mosca achieved, Mosca currently only supports QoS 1

Simple note, if sending a temporary message, such as sending a message to a topic all online equipment, lost, then it does not matter, 0 on it (when the client logs to indicate support of QoS levels while sending the message when this message also indicates the level of support QoS), if needed to ensure that the client can receive messages, you need to specify QoS 1, if the client does not need to join simultaneous online also can receive the message, when the client logs to the effectiveness of the specified session, receiving offline messages need to specify the server you want to keep session state clients.

Based on IOS client MQTT-Client-Framework of

Existing client sdk analysis, basically divided into two categories: C transplanted from libraries, such as mosquitto, one is implemented objc native or swift.
Sdk various contrast follows, I use is MQTT-Client, using swift students can use CocoaMQTT, this is also the author of sdk-side implementation of the service of emqtt.

Name Type Programming Language Code
Paho Original C Open-Source. Eclipse project
IBM Original C Close Source. IBM SDK
mosquitto Original C Open-Source. Eclipse project
MQTTKit Wrapper (Mosquitto) Objective-C Open-Source. Github
Marquette Wrapper (Mosquitto) Objective-C Open-Source. Github
Moscapsule Wrapper (Mosquitto) Swift Open-Source. Github
Musqueteer Wrapper (Mosquitto) Objective-C
MQTT-Client Native Objective-C Open-Source. Github
MQTTSDK Native Objective-C
CocoaMQTT Native Swift Open-Source. Github

Possible problems described below, Apple prohibits third-party network library using the mobile network.

If you are trying to use MQTT for an iOS application I will highly recommend you to use a native (Objective-C/Swift) iOS library. Using C or wrapper libraries usually means you are using POSIX networking calls at some point. Apple forbids the use of third party networking libraries from using the mobile internet antenna. Thus if you use Paho or something similar, you can only use MQTT when you are connected to a WiFi network.
源引自https://github.com/relayr/apple-mqtt-example

Integration Steps

MQTT-Client support pod, easily and quickly integrated into the project. Simply under the scenario, app will produce different business data on each of the terminal installation, and business data needs to be seen on each terminal app, so the need to synchronize business data of all terminals. Mqtt message transmission are carried out by topic, topic needs to be created, according to mqtt implementation topic is no separate creation, and subscribe topic is bound. That is as long subscribed to a topic, the server first determines whether there exist topic, if any, the current client is added to the subscription list, if not, then you create a topic, while adding yourself to the subscription list.

establish connection

If the app need advice transmitting data in a plurality of pages using a single embodiment mode, establishing a global connection, multiple connections. Because every time you connect to the server is very resource-intensive. Code to establish the following connections:

1
* = SessionManager MQTTSessionManager [[MQTTSessionManager alloc] the init]; 
 [SessionManager ConnectTo: @ "192.168.1.4" // server address 
                      port: 1883 // service port number 
                       tls: false // whether to use the tls protocol, mosca support of tls If you want to use the set to true 
                 Keepalive: 60 // heartbeat time, in seconds, to send heartbeat packets every fixed time 
                     clean: false // session whether to clear, the need to pay attention, if taste false, representatives remain logged in, if the client Log off once again you can receive offline messages 
                      auth: true // whether to use the login authentication, and user and pass parameters using a combination of the following 
                      user: _userName // username 
                      pass: _passwd // password 
                 willTopic: @ "" // below four parameter sets if the client is offline messages sent to other clients, which is the current parameter used for transmitting an offline message topic, offline messages are herein refers to a message sent after the dropped customer to take away line 
                      will: @ " "// offline messages custom format can be a good agreement
                   willQos: 0 // receiving offline messages level
            willRetainFlag: false 
              withClientId:]; // client id, needs to be noted that this id needs globally unique, because the server is based on this to differentiate the client after default an id login, if there is another connection Log in with this id, a connection will be kicked off the assembly line

Subscribe and send messages

Once the connection is established later can subscribe topic and send messages, send messages and subscription code is as follows:

1
// Feed Topic 
sessionManager.subscriptions = [[NSMutableDictionary the alloc] the init]; 
[sessionManager.subscriptions the setObject: [the NSNumber numberWithInt:. 1] 
                                                                     forKey: _topic]; 
// send a message, the return value is greater than 0 represents the transmission success msgid 
UInt16 msgid = [ sessionManager sendData: [msg dataUsingEncoding: NSUTF8StringEncoding ] // message body to be sent 
                                                                          topic: topic // send messages to the topic to which                                                                         
                                                                            qos: 1 // message level 
                                                                         retain: false];

Receive messages

Receiving a delegation message has achieved to realize the following message received commission MQTTSessionManagerDelegate

1
- (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained;

 

The topic can distinguish between different messages

Monitor the connection status

A register observer determines a different state acquired connection state

1
// Register observer, remember to remove the observer when leaving the page 
- (void) viewWillAppear: (BOOL) Animated { 
    [Super viewWillAppear: Animated]; 
    
    [SessionManager addObserver: Self 
                    forKeyPath: @ "State" 
                       Options: NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew 
                       context : nil]; 
} 


- (void) the observeValueForKeyPath: (NSString *) keyPath ofObject: (ID) Object Change: (NSDictionary *) Change context: (void *) context { 
    Switch (sessionManager.state) { 
        Case MQTTSessionManagerStateClosed: // connection It has closed 
            BREAK; 
        Case MQTTSessionManagerStateClosing: // connection is closed  
            break;
        case MQTTSessionManagerStateConnected: // connected 
            BREAK; 
        Case MQTTSessionManagerStateConnecting: // Connecting the 
            BREAK; 
        Case MQTTSessionManagerStateError: // exception 
            BREAK; 
        Case MQTTSessionManagerStateStarting: // Start connection 
        default: 
            BREAK; 
    } 
}

 

mqtt protocol itself supports reconnection, in addition to a separate description of this sdk to exit the app automatically disconnected after the background, when returned to the front desk will automatically reconnect

Android client and integrated js

Js Android client and the client can use at the polo program, address http://www.eclipse.org/paho/
sdk I used for testing:
Android  https://www.eclipse.org/paho/clients/android/
JS  https://www.eclipse.org/paho/clients/js/

DETAILED IOS with the integration steps, only need to pay attention IOS parameters mentioned above can be a

Written in the last

Recent weather in the north continues to deteriorate, severe haze can not go to the point, the mood is also very low, powerlessness and more intense, I have no mind to write, ready to leave this place, and so on to write other calm down things right. The content is expected to write something Raspberry Pi and Docker related.

 


转载: http://targe.me/2016/01/02/mqtt-three/

Guess you like

Origin www.cnblogs.com/youyong/p/11388401.html