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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值