MQTTClient的使用

###MQTTClient的使用
iOS环境下开发 MQTT 客户端程序,一般依赖稳定的第三方 FrameWork,由于涉及网络数据传输,建议选择 Object-c 原生的框架,比如 MQTT-Client-Framework。
现在一般常用的有两个MQTT

  1. MQTTKit
  2. MQTTClient
    不过MQTTKit貌似很长时间不维护了, 使用较多的是MQTTClient。

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<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.接受消息

/** 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);

转载于:https://my.oschina.net/u/3729363/blog/1605342

展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读