###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);