MQTT-Client-FrameWork 包提供的客户端类有 MQTTSession 和 MQTTSessionManager,后者维持静态资源,并且已经封装好自动重连等逻辑。初始化时只须要传入相关的网络参数。 下面是 MQTTSessionManager的使用详解服务器
1.创建链接网络
NSString *clientId = [UIDevice currentDevice].identifierForVendor.UUIDString; MQTTSessionManager *sessionManager = [[MQTTSessionManager alloc] init]; BOOL will = YES; NSString *willTopic = nil; NSData *msg = nil; MQTTQosLevel qos = 0; BOOL willRetainFlag = NO; if (will) { willTopic = @"chat"; msg = [@"user1离线" dataUsingEncoding:NSUTF8StringEncoding]; qos = 1; willRetainFlag = YES; } /** host: 服务器地址 port: 服务器端口 tls: 是否使用tls协议, keepalive: 心跳时间,单位秒,每隔固定时间发送心跳包,sdk默认是60s clean: session是否清除,若是是false,下次创建链接的时候会保持上次全部的订阅,而且收到离线时的全部消息, auth: 是否使用登陆验证 user: 用户名 pass: 密码 willTopic: 遗嘱主题名 willMsg: 自定义的遗嘱消息 willQos: 发送遗嘱线消息的级别 clientId:客户端id,须要特别指出的是这个id须要全局惟一,由于服务端是根据这个来区分不一样的客户端的,默认状况下一个id登陆后,再使用此id登陆会把上一个踢下线 */ [sessionManager connectTo:@"45.63.124.196" port:1883 tls:false keepalive:30 //心跳间隔不得大于120s clean:true auth:true user:@"itouchtv1" pass:@"password" will:will willTopic:willTopic willMsg:msg willQos:qos willRetainFlag:false withClientId:clientId]; sessionManager.delegate = self; self.sessionManager = sessionManager;
2.订阅主题session
订阅主题就是给subscriptions赋值,类型为字典,没有失败回调ide
//阅读失败此处并无回调失败处理 NSDictionary *dict = @{@"IM_topicA" : @"1",}; self.sessionManager.subscriptions = dict;
3.接受消息代理
接受消息是实现MQTTSessionManagerDelegate的代理的方法code
// 获取服务器返回数据 - (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained { NSLog(@"------------->>%@",topic); NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"=== %@",dataString); // 进行消息处理 [self handleMessage:data onTopic:topic]; }
4.发送消息server
NSString *content = @"一条消息"; NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding]; NSString *topic = @"IM_topicA"; /* 发送消息 sendData:要发送的消息体 topic:要往哪一个topic发送消息 qos:消息级别 retain:设置消息retain属性 return msgid:大于0表明发送成功 */ UInt16 msgid = [self.sessionManager sendData:data topic:topic qos:1 retain:false];
5.监听当前链接状态ip
// 监听当前链接状态 [self.sessionManager addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { switch (self.sessionManager.state) { case MQTTSessionManagerStateClosed: NSLog(@"链接已经关闭"); break; case MQTTSessionManagerStateClosing: NSLog(@"链接正在关闭"); break; case MQTTSessionManagerStateConnected: NSLog(@"已经链接"); break; case MQTTSessionManagerStateConnecting: NSLog(@"正在链接中"); break; case MQTTSessionManagerStateError: { NSString *errorCode = self.sessionManager.lastErrorCode.localizedDescription; NSLog(@"链接异常 ----- %@",errorCode); } break; case MQTTSessionManagerStateStarting: NSLog(@"开始链接"); break; default: break; } }