美文网首页
iOS MQTTClient使用记录

iOS MQTTClient使用记录

作者: 烟雨酱南 | 来源:发表于2020-04-02 16:38 被阅读0次

    MQTT是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分。该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和致动器(比如通过Twitter让房屋联网)的通信协议

    MQTTClient Cocoapods安装

    pod 'MQTTClient'
    

    1.连接

    self.manager = [[MQTTSessionManager alloc]init];
        self.manager.delegate = self;
        [self.manager connectTo:@"地址" port:@"端口号" tls:NO keepalive:60 clean:YES auth:YES user:nil pass:nil will:NO willTopic:nil willMsg:nil willQos:(MQTTQosLevelAtMostOnce) willRetainFlag:NO withClientId:nil securityPolicy:nil certificates:nil protocolLevel:(MQTTProtocolVersion311) connectHandler:^(NSError *error) {
            if (error == nil) {
                NSLog(@"MQTT连接成功");
            }
        }];
        //观察连接状态
        [self.manager addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptionNew) context:nil];
    

    2.连接状态

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
        switch (self.manager.state) {
            case MQTTSessionManagerStateClosed:
                NSLog(@"MQTT&&&&&&&&&&&&&&closed");
                break;
            case MQTTSessionManagerStateClosing:
                NSLog(@"MQTT&&&&&&&&&&&&&&closing");
                break;
            case MQTTSessionManagerStateConnected:
                NSLog(@"MQTT&&&&&&&&&&&&&&connected");
                break;
            case MQTTSessionManagerStateConnecting:
                NSLog(@"MQTT&&&&&&&&&&&&&&connecting");
                break;
            case MQTTSessionManagerStateError:
                NSLog(@"MQTT&&&&&&&&&&&&&&error");
                break;
            case MQTTSessionManagerStateStarting:
                NSLog(@"MQTT&&&&&&&&&&&&&&starting");
                break;
                
            default:
                break;
        }
    

    3.订阅channel

    self.manager.subscriptions = @{@"指定的channel":[NSNumber numberWithInt:MQTTQosLevelAtMostOnce]};
    

    4.发送消息

    [self.manager sendData:data topic:@"指定的channel" qos:(MQTTQosLevelAtMostOnce) retain:NO];
    

    5.收到MQTT消息

    - (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained{
    }
    
    

    具体使用可以查看GitHurb说明MQTT-Client-Framework.

    相关文章

      网友评论

          本文标题:iOS MQTTClient使用记录

          本文链接:https://www.haomeiwen.com/subject/zrgxphtx.html