iOS MQTT 간단한 사용 절차
9588 단어 ios 개발 수기
EMQ - 백만 대 오픈 소스 MQTT 메시지 서버
EMQ(Erlang/Enterprise/Elastic MQTT Broker)는 Erlang/OTP 플랫폼을 기반으로 개발된 소스 사물인터넷 MQTT 메시지 서버입니다.Erlang/OTP는 뛰어난 소프트 실시간(Soft-Realtime), 저연시(Low-Latency), 분산(Distributed) 언어 플랫폼입니다.MQTT는 경량(Lightweight), 게시 구독 모드(PubSub)의 사물인터넷 메시지 프로토콜이다.
EMQ 프로젝트 설계 목표는 이동 단말기 또는 사물인터넷 단말기의 대량의 MQTT 연결을 탑재하고 대량의 사물인터넷 장치 간의 빠른 시간 지연 메시지 루트를 실현하는 것이다.
QTT SDK를 여러 가지로 선택
다음은 두 가지 MQTTKit와 MQTT-Client-Framework 두 가지 모두 OC 사용 Swift 버전입니다. 참고로 CocoaMQTT
1、 ** MQTTKit **
는 업데이트되지 않았지만 기본 사용은 문제없습니다.pod ‘MQTTKit’
헤더 파일
#import #define WEAKSELF __typeof(&*self) __weak weakSelf = self; @property (nonatomic, strong) MQTTClient *client;
링크 초기화
WEAKSELF
NSString *clientID = @" client - id ";
MQTTClient *client = [[MQTTClient alloc] initWithClientId:StrFormat(@"%@", clientID)];
client.username = @"username";
client.password = @"password";
client.cleanSession = false;
client.keepAlive = 20;
client.port = 11883;//
self.client = client;
// MQTT
[client connectToHost:@" MQTT URL" completionHandler:^(MQTTConnectionReturnCode code) {
if (code == ConnectionAccepted) {
NSLog(@" MQTT ???");
//
[weakSelf.client subscribe:@" " withQos:AtLeastOnce completionHandler:^(NSArray *grantedQos) {
DLog(@" %@",grantedQos);
}];
}else if (code == ConnectionRefusedBadUserNameOrPassword){
NSLog(@"MQTT ");
} else if (code == ConnectionRefusedUnacceptableProtocolVersion){
NSLog(@"MQTT ");
}else if (code == ConnectionRefusedIdentiferRejected){
NSLog(@"MQTT ");
}else if (code == ConnectionRefusedServerUnavailable){
NSLog(@"MQTT ");
}else {
NSLog(@"MQTT ");
}
}];
//
client.messageHandler = ^(MQTTMessage *message) {
NSString *jsonStr = [[NSString alloc] initWithData:message.payload encoding:NSUTF8StringEncoding];
NSLog(@"EasyMqttService mqtt connect success %@",jsonStr);
};
주제에 가입
//
-(void)subscribeType:(NSString *)example{
//
[self.client subscribe:@" " withQos:AtMostOnce completionHandler:^(NSArray *grantedQos) {
NSLog(@" %@",grantedQos);
}];
}
QTTKit 끄기
-(void)closeMQTTClient{
WEAKSELF
[self.client disconnectWithCompletionHandler:^(NSUInteger code) {
// The client is disconnected when this completion handler is called
NSLog(@"MQTT client is disconnected");
[weakSelf.client unsubscribe:@" " withCompletionHandler:^{
NSLog(@" ");
}];
}];
}
메시지 보내기
[self.client publishString:postMsg toTopic:@" " withQos:AtLeastOnce retain:NO completionHandler:^(int mid) {
if (cmd != METHOD_SOCKET_CHAT_TO) {
NSLog(@" %d",mid);
}
}];
2、 ** MQTTClient **
MQTTClient , SSL
pod'MQTTClient'websocket
방식으로pod'MQTTClient/MinL'pod'MQTTClient/ManagerL'pod'MQTTClient/WebsocketL'을 연결합니다.헤더 파일
#importwebsocket
추가해야 할 헤더 파일 #import #define WEAKSELF _typeof(&*self) __weak weakSelf = self; @property (nonatomic, strong) MQTTSession *mySession;
링크 초기화
#import "MQTTClient.h"
\@interface MyDelegate : ...
...
MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init];
transport.host = @"localhost";
transport.port = 1883;
MQTTSession *session = [[MQTTSession alloc] init];
session.transport = transport;
session.delegate = self;
[session connectAndWaitTimeout:30]; //this is part of the synchronous API
websocket
WEAKSELF
NSString *clientID = @" client - id ";
MQTTWebsocketTransport *transport = [[MQTTWebsocketTransport alloc] init];
transport.host = @" MQTT ";
transport.port = 8083; //
transport.tls = YES; // YES SSL SDK
MQTTSession *session = [[MQTTSession alloc] init];
NSString *linkUserName = @"username";
NSString *linkPassWord = @"password";
[session setUserName:linkUserName];
[session setClientId:clientID];
[session setPassword:linkPassWord];
[session setKeepAliveInterval:5];
session.transport = transport;
session.delegate = self;
self.mySession = session;
[self reconnect];
[self.mySession addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; //
웹소켓 응답 이벤트 감청
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
switch (self.mySession.status) {
case MQTTSessionManagerStateClosed:
NSLog(@" ");
break;
case MQTTSessionManagerStateClosing:
NSLog(@" ");
break;
case MQTTSessionManagerStateConnected:
NSLog(@" ");
break;
case MQTTSessionManagerStateConnecting:
NSLog(@" ");
break;
case MQTTSessionManagerStateError: {
// NSString *errorCode = self.mySession.lastErrorCode.localizedDescription;
NSString *errorCode = self.mySession.description;
NSLog(@" ----- %@",errorCode);
}
break;
case MQTTSessionManagerStateStarting:
NSLog(@" ");
break;
default:
break;
}
}
session Delegate 프로토콜
-(void)handleEvent:(MQTTSession *)session event:(MQTTSessionEvent)eventCode error:(NSError *)error{
if (eventCode == MQTTSessionEventConnected) {
NSLog(@"2222222 MQTT ");
}else if (eventCode == MQTTSessionEventConnectionRefused) {
NSLog(@"MQTT ");
}else if (eventCode == MQTTSessionEventConnectionClosed){
NSLog(@"MQTT ");
}else if (eventCode == MQTTSessionEventConnectionError){
NSLog(@"MQTT ");
}else if (eventCode == MQTTSessionEventProtocolError){
NSLog(@"MQTT ");
}else{//MQTTSessionEventConnectionClosedByBroker
NSLog(@"MQTT ");
}
if (error) {
NSLog(@" -- %@",error);
}
}
-(void)newMessage:(MQTTSession *)session data:(NSData *)data onTopic:(NSString *)topic qos:(MQTTQosLevel)qos retained:(BOOL)retained mid:(unsigned int)mid
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"EasyMqttService mqtt connect success %@",dic);
//
}
주제에 가입
//
[session subscribeToTopic:@"example/#" atLevel:2 subscribeHandler:^(NSError *error, NSArray *gQoss){
if (error) {
NSLog(@"Subscription failed %@", error.localizedDescription);
} else {
NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
}
}]; // this is part of the block API
websocket
- (void)subscibeToTopicAction {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self subscibeToTopic:@" "];
});
});
}
-(void)subscibeToTopic:(NSString *)topicUrl
{
// self.manager.subscriptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:MQTTQosLevelAtMostOnce] forKey:topicUrl];
[self.mySession subscribeToTopic:topicUrl atLevel:MQTTQosLevelAtMostOnce subscribeHandler:^(NSError *error, NSArray *gQoss) {
if (error) {
NSLog(@" %@ %@",topicUrl,error);
}else
{
NSLog(@" %@ g1oss %@",topicUrl,gQoss);
dispatch_async(dispatch_get_main_queue(), ^{
//
});
};
}];
}
QTT-Client 닫기
-(void)closeMQTTClient{
[self.mySession disconnect];
[self.mySession unsubscribeTopics:@[@" "] unsubscribeHandler:^(NSError *error) {
if (error) {
DLog(@" ");
}else{
DLog(@" ");
}
}];
}
메시지 보내기
[self.mySession publishData:jsonData onTopic:@" " retain:NO qos:MQTTQosLevelAtMostOnce publishHandler:^(NSError *error) {
if (error) {
NSLog(@" - %@",error);
}else{
NSLog(@" ");
}
}];