MQTT实现长连接,IM最简单实例

时间:2022-11-11 10:48:49

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