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

  • 相关阅读:
    Redis事务和锁
    11/6笔记 补充(Redis持久化,RDB&&AOF)
    11/6随笔
    Redis 安装教程
    Redis通用指令和第一个Jedis程序的实现
    Redis学习第二天
    SpringBoot学习笔记
    1000行代码手写服务器
    log4j创建实例异常
    寒假阅读人月神话3
  • 原文地址:https://www.cnblogs.com/huntaiji/p/4086607.html
Copyright © 2011-2022 走看看