MQTTClient的使用(二)

MQTT-Client-FrameWork 包提供的客戶端類有 MQTTSession 和 MQTTSessionManager,後者維持靜態資源,並且已經封裝好自動重連等邏輯。初始化時只須要傳入相關的網絡參數。 下面是 MQTTSessionManager的使用詳解服務器

1.創建鏈接網絡

NSString *clientId = [UIDevice currentDevice].identifierForVendor.UUIDString;
    MQTTSessionManager *sessionManager = [[MQTTSessionManager alloc] init];
    
    BOOL will = YES;
    NSString *willTopic = nil;
    NSData *msg = nil;
    MQTTQosLevel qos = 0;
    BOOL willRetainFlag = NO;
    if (will) {
        willTopic = @"chat";
        msg = [@"user1離線" dataUsingEncoding:NSUTF8StringEncoding];
        qos = 1;
        willRetainFlag = YES;
    }

    /**
      host: 服務器地址
      port: 服務器端口
      tls:  是否使用tls協議,
      keepalive: 心跳時間,單位秒,每隔固定時間發送心跳包,sdk默認是60s
      clean: session是否清除,若是是false,下次創建鏈接的時候會保持上次全部的訂閱,而且收到離線時的全部消息,
      auth: 是否使用登陸驗證
      user: 用戶名
      pass: 密碼
      willTopic: 遺囑主題名
      willMsg: 自定義的遺囑消息
      willQos: 發送遺囑線消息的級別
      clientId:客戶端id,須要特別指出的是這個id須要全局惟一,由於服務端是根據這個來區分不一樣的客戶端的,默認狀況下一個id登陸後,再使用此id登陸會把上一個踢下線
*/
    [sessionManager connectTo:@"45.63.124.196"
                         port:1883
                          tls:false
                    keepalive:30  //心跳間隔不得大於120s
                        clean:true
                         auth:true
                         user:@"itouchtv1"
                         pass:@"password"
                         will:will
                    willTopic:willTopic
                      willMsg:msg
                      willQos:qos
               willRetainFlag:false
                 withClientId:clientId];
    sessionManager.delegate = self;
    self.sessionManager = sessionManager;

2.訂閱主題session

訂閱主題就是給subscriptions賦值,類型爲字典,沒有失敗回調ide

//閱讀失敗此處並無回調失敗處理
    NSDictionary *dict = @{@"IM_topicA" : @"1",};
    self.sessionManager.subscriptions = dict;

3.接受消息代理

接受消息是實現MQTTSessionManagerDelegate的代理的方法code

// 獲取服務器返回數據
- (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained {
    NSLog(@"------------->>%@",topic);
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"=== %@",dataString);
    
    // 進行消息處理
    [self handleMessage:data onTopic:topic];
}

4.發送消息server

NSString *content = @"一條消息";
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSString *topic = @"IM_topicA";
   /*
   發送消息  
   		sendData:要發送的消息體
   		topic:要往哪一個topic發送消息
   		qos:消息級別
   		retain:設置消息retain屬性
   		
   		return msgid:大於0表明發送成功
   */
   
    UInt16 msgid = [self.sessionManager sendData:data
                                           topic:topic
                                             qos:1
                                          retain:false];

5.監聽當前鏈接狀態ip

// 監聽當前鏈接狀態
    [self.sessionManager addObserver:self
                          forKeyPath:@"state"
                             options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                             context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    switch (self.sessionManager.state) {
        case MQTTSessionManagerStateClosed:
            NSLog(@"鏈接已經關閉");
            break;
        case MQTTSessionManagerStateClosing:
            NSLog(@"鏈接正在關閉");
            
            break;
        case MQTTSessionManagerStateConnected:
            NSLog(@"已經鏈接");
            
            break;
        case MQTTSessionManagerStateConnecting:
            NSLog(@"正在鏈接中");
            
            break;
        case MQTTSessionManagerStateError: {
            NSString *errorCode = self.sessionManager.lastErrorCode.localizedDescription;
            NSLog(@"鏈接異常 ----- %@",errorCode);
        }
            
            break;
        case MQTTSessionManagerStateStarting:
            NSLog(@"開始鏈接");
            break;
        default:
            break;
    }
}
相關文章
相關標籤/搜索