----- 更新 目前使用了 MQTTSessionManage 類 來代替之前的 MQTTSession -----
在最近的一個(gè)項(xiàng)目中,使用到了mqtt協(xié)議规惰,并且需要SSL加密單向驗(yàn)證兼贸,故把自己的所寫記錄下乏矾。
第一步:安裝
目前泼菌,使用的是Pod生成的MQTTClient第三方庫泳挥,直接下載就行 pod 'MQTTClient'
第二步:綁定
綁定前需要設(shè)置幾個(gè)屬性沽瘦,主要有:
帳號(hào)柬甥、密碼、clientId其垄、ip苛蒲、端口。
其次绿满,還要注意這個(gè)庫是沒有連接中斷自動(dòng)重連的臂外。所以需要監(jiān)聽他的狀態(tài)。
#pragma mark - 綁定
- (void)bindWithUserName:(NSString *)username password:(NSString *)password cliendId:(NSString *)cliendId isSSL:(BOOL)isSSL{
self.username = username;
self.password = password;
self.cliendId = cliendId;
self.SSL = isSSL;
/*
self.mySession = [[MQTTSession alloc]initWithClientId:self.cliendId userName:self.username password:self.password keepAlive:60 cleanSession:YES will:NO willTopic:nil willMsg:nil willQoS:MQTTQosLevelAtLeastOnce willRetainFlag:NO protocolLevel:4 queue:dispatch_get_main_queue() securityPolicy:[self customSecurityPolicy] certificates:nil];
self.isDiscontent = NO;
self.mySession.delegate = self;
[self.mySession connectToHost:AddressOfMQTTServer port:self.isSSL?PortOfMQTTServerWithSSL:PortOfMQTTServer usingSSL:isSSL];
[self.mySession addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
*/
[self.mySessionManager connectTo:AddressOfMQTTServer
port:self.isSSL?PortOfMQTTServerWithSSL:PortOfMQTTServer
tls:self.isSSL
keepalive:60
clean:YES
auth:YES
user:self.username
pass:self.password
will:NO
willTopic:nil
willMsg:nil
willQos:MQTTQosLevelAtLeastOnce
willRetainFlag:NO
withClientId:self.cliendId
securityPolicy:[self customSecurityPolicy]
certificates:nil
protocolLevel:4
connectHandler:nil];
self.isDiscontent = NO;
self.mySessionManager.subscriptions = self.subedDict;
}
- (MQTTSSLSecurityPolicy *)customSecurityPolicy
{
MQTTSSLSecurityPolicy *securityPolicy = [MQTTSSLSecurityPolicy policyWithPinningMode:MQTTSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
securityPolicy.validatesCertificateChain = YES;
securityPolicy.validatesDomainName = NO;
return securityPolicy;
}
當(dāng)綁定完成之后喇颁,會(huì)打印出以下的信息漏健。
第三步:獲取狀態(tài)
#pragma mark ---- 狀態(tài)
- (void)sessionManager:(MQTTSessionManager *)sessionManager didChangeState:(MQTTSessionManagerState)newState {
switch (newState) {
case MQTTSessionManagerStateConnected:
NSLog(@"eventCode -- 連接成功");
break;
case MQTTSessionManagerStateConnecting:
NSLog(@"eventCode -- 連接中");
break;
case MQTTSessionManagerStateClosed:
NSLog(@"eventCode -- 連接被關(guān)閉");
break;
case MQTTSessionManagerStateError:
NSLog(@"eventCode -- 連接錯(cuò)誤");
break;
case MQTTSessionManagerStateClosing:
NSLog(@"eventCode -- 關(guān)閉中");
break;
case MQTTSessionManagerStateStarting:
NSLog(@"eventCode -- 連接開始");
break;
default:
break;
}
}
第四步:訂閱命令
#pragma mark - 訂閱
- (void)subscribeTopic:(NSString *)topic handler:(SubscribeTopicHandler)handler{
NSLog(@"當(dāng)前需要訂閱-------- topic = %@",topic);
if (![self.subedDict.allKeys containsObject:topic]) {
[self.subedDict setObject:[NSNumber numberWithLong:MQTTQosLevelAtLeastOnce] forKey:topic];
NSLog(@"訂閱字典 ----------- = %@",self.subedDict);
self.mySessionManager.subscriptions = self.subedDict;
}
else {
NSLog(@"已經(jīng)存在,不用訂閱");
}
取消訂閱
#pragma mark - 取消訂閱
- (void)unsubscribeTopic:(NSString *)topic {
NSLog(@"當(dāng)前需要取消訂閱-------- topic = %@",topic);
if ([self.subedDict.allKeys containsObject:topic]) {
[self.subedDict removeObjectForKey:topic];
NSLog(@"更新之后的訂閱字典 ----------- = %@",self.subedDict);
self.mySessionManager.subscriptions = self.subedDict;
}
else {
NSLog(@"不存在橘霎,無需取消");
}
}
發(fā)布消息
#pragma mark - 發(fā)布消息
- (void)sendDataToTopic:(NSString *)topic dict:(NSDictionary *)dict {
NSLog(@"發(fā)送命令 topic = %@ dict = %@",topic,dict);
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
[self.mySessionManager sendData:data topic:topic qos:MQTTQosLevelAtLeastOnce retain:NO];
}
數(shù)據(jù)接收回調(diào)
#pragma mark MQTTSessionManagerDelegate
- (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained {
if (self.delegate && [self.delegate respondsToSelector:@selector(MQTTClientModel_handleMessage:onTopic:retained:)]) {
[self.delegate MQTTClientModel_handleMessage:data onTopic:topic retained:retained];
}
}
主動(dòng)斷開
- (void)disconnect {
self.isDiscontent = YES;
// self.isContented = NO;
[self.mySessionManager disconnectWithDisconnectHandler:^(NSError *error) {
NSLog(@"斷開連接 error = %@",[error description]);
}];
[self.mySessionManager setDelegate:nil];
self.mySessionManager = nil;
}
重連
- (void)reConnect {
if (self.mySessionManager && self.mySessionManager.port) {
self.mySessionManager.delegate = self;
self.isDiscontent = NO;
[self.mySessionManager connectToLast:^(NSError *error) {
NSLog(@"重新連接 error = %@",[error description]);
}];
self.mySessionManager.subscriptions = self.subedDict;
}
else {
[self bindWithUserName:self.username password:self.password cliendId:self.cliendId isSSL:self.isSSL];
}
}
其他
目前使用下來沒遇到太大問題蔫浆,基本能滿足項(xiàng)目所需。