zoukankan      html  css  js  c++  java
  • MQTT实现长连接,IM最简单实例

    更多技术性文章请关注 合伙呀

    1,引入MqttSDK.

    2, 头文件

    #import "MQTTSession.h"

    //定义主题
    #define kTopic @"lichanghong"
    //服务器ip
    #define kIP @"192.168.2.204"

    @interface ViewController : UIViewController
    @property (nonatomic, strong) MQTTSession *session;

    @end

    3,实现

    - (void)viewDidLoad {
      [super viewDidLoad];
      //连接
      _session = [[MQTTSession alloc] initWithClientId:@"12345"];
      [_session setDelegate:self];
      [_session connectToHost:@"192.168.2.204" port:1883];
      // [_session publishDataAtLeastOnce:[@"publish data..." dataUsingEncoding:NSUTF8StringEncoding] onTopic:@"lichanghong"];
    }

    #pragma mark - MQtt Callback methods

    - (void)session:(MQTTSession*)sender handleEvent:(MQTTSessionEvent)eventCode {
      switch (eventCode) {
        case MQTTSessionEventConnected:
          [_session subscribeTopic:@"lichanghong"];
          NSLog(@"connected");
          
          break;
        case MQTTSessionEventConnectionRefused:
          NSLog(@"connection refused");
          break;
        case MQTTSessionEventConnectionClosed:
          NSLog(@"connection closed");
          break;
        case MQTTSessionEventConnectionError:
          NSLog(@"connection error");
          NSLog(@"reconnecting...");
          // Forcing reconnection
          [_session connectToHost:kIP port:1883];
          break;
        case MQTTSessionEventProtocolError:
          NSLog(@"protocol error");
          break;
      }
    }

    - (void)session:(MQTTSession*)sender  newMessage:(NSData*)data  onTopic:(NSString*)topic {
      NSLog(@"new message, %lu bytes, topic=%@", (unsigned long)[data length], topic);
      NSString *payloadString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"data: %@ %@", payloadString, data);
    }

  • 相关阅读:
    慢性肾炎患者的家庭养护
    中国居民五谷膳食指南
    第二单元丨对环境的察觉
    一个人是否靠谱,闭环很重要
    打赢营销胜仗
    治本修身──中醫內分泌調節養生法
    理想的激励
    卓越演讲:打动听众必知必会的策略和方法(原书第3版)
    每日一题_191008
    每日一题_191007
  • 原文地址:https://www.cnblogs.com/huntaiji/p/4086607.html
Copyright © 2011-2022 走看看