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.订阅主题
订阅主题就是给subscriptions赋值,类型为字典,没有失败回调
//阅读失败此处并没有回调失败处理
NSDictionary *dict = @{@"IM_topicA" : @"1",};
self.sessionManager.subscriptions = dict;
3.接受消息
接受消息是实现MQTTSessionManagerDelegate的代理的方法
// 获取服务器返回数据
- (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.发送消息
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.监听当前连接状态
// 监听当前连接状态
[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;
}
}