###MQTTClient的使用
iOS環境下開發 MQTT 客戶端程序,通常依賴穩定的第三方 FrameWork,因爲涉及網絡數據傳輸,建議選擇 Object-c 原生的框架,好比 MQTT-Client-Framework。
如今通常經常使用的有兩個MQTTgit
MQTT-Client-FrameWork 包提供的客戶端類有 MQTTSession 和 MQTTSessionManager,咱們先使用基本MQTTSession類實現MQTT的鏈接
1.創建鏈接github
MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init]; transport.host = self.addTextField.text; transport.port = self.portTextField.text.intValue; MQTTSession *session = [[MQTTSession alloc] init]; session.transport = transport; session.delegate = self; //this is part of the synchronous API [session connectAndWaitTimeout:30.0]; self.session = session;
2.訂閱主題網絡
[self.session subscribeToTopic:topicName atLevel:MQTTQosLevelExactlyOnce subscribeHandler:^(NSError *error, NSArray<NSNumber *> *gQoss) { if (error) { NSLog(@"====>訂閱失敗:%@", error.localizedDescription); } else { NSLog(@"====>訂閱成功:%@", gQoss); dispatch_async(dispatch_get_main_queue(), ^{ self.subedLabel.text = [NSString stringWithFormat:@"%@,%@", self.subedLabel.text, topicName]; }); } }]
3.接受消息session
/** gets called when a new message was received @param session the MQTTSession reporting the new message @param data the data received, might be zero length @param topic the topic the data was published to @param qos the qos of the message @param retained indicates if the data retransmitted from server storage @param mid the Message Identifier of the message if qos = 1 or 2, zero otherwise */ - (void)newMessage:(MQTTSession *)session data:(NSData *)data onTopic:(NSString *)topic qos:(MQTTQosLevel)qos retained:(BOOL)retained mid:(unsigned int)mid;
4.發送消息框架
NSString *content = self.pubMsgTextField.text; NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding]; NSString *topic = self.pubTopicTextField.text; UInt16 result = [self.session publishData:data onTopic:topic retain:YES qos:1 publishHandler:^(NSError *error) { if (error) { NSLog(@"====> 發送失敗"); } else { NSLog(@"====> 發送成功"); dispatch_async(dispatch_get_main_queue(), ^{ self.pubMsgTextField.text = @""; }); } }]; NSLog(@"====> publish resutl:%d", result);