2019独角兽企业重金招聘Python工程师标准>>>
###MQTTClient的使用
iOS环境下开发 MQTT 客户端程序,一般依赖稳定的第三方 FrameWork,由于涉及网络数据传输,建议选择 Object-c 原生的框架,比如 MQTT-Client-Framework。
现在一般常用的有两个MQTT
- MQTTKit
- MQTTClient
不过MQTTKit貌似很长时间不维护了, 使用较多的是MQTTClient。
- 集成MQTTClient
MQTT-Client-Framework
MQTT-Client-FrameWork 包提供的客户端类有 MQTTSession 和 MQTTSessionManager,我们先使用基本MQTTSession类实现MQTT的连接
1.建立连接
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 *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.接受消息
/** 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);