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);
    }

  • 相关阅读:
    Asp.net 连接池使用
    关于ASP.NET页面打印技术的总结
    Asp.net页面传值总结
    C#委托
    ASP.NET状态存储管理九大兵器
    JavaScript取ASP.NET中服务器端数据的方法
    DSOFramer.ocx 控件使用
    C#2.0 泛型学习(入门)
    黑马程序员——Java基础String与StringBuilder
    黑马程序员——Java基础语法关键字、常量、变量、运算符
  • 原文地址:https://www.cnblogs.com/huntaiji/p/4086607.html
Copyright © 2011-2022 走看看