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

  • 相关阅读:
    Linux 一块网卡配置多个IP的方法
    Nginx详解篇
    Nginx故障排错及一个网站小实例
    Nginx web 服务器 安装篇
    一些看起来比较专业的工具
    Linux 下软件的安装方法
    Mysq登陆后执行命令提示You must SET PASSWORD before executing this statement
    Linux-Centos 虚拟机安装
    Mysql的多种安装方法———rpm安装
    etcd安装和简单使用
  • 原文地址:https://www.cnblogs.com/huntaiji/p/4086607.html
Copyright © 2011-2022 走看看