1,创建单视图项目,pod search mqtt找到一个库,然后在项目目录下pod init 出Podfile
2,pod install 安装mqtt库
3,主要代码:
#import "MQTTClient.h"
设置<MQTTSessionDelegate>
//初始化一个传输类型的实例
MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init];
transport.host = @"localhost";
transport.port = 1883;
//创建一个任务
MQTTSession *session = [[MQTTSession alloc] init];
//设置任务的传输类型
session.transport = transport;
//设置任务的代理为当前类
session.delegate = self;
//设置登录账号
session.clientId = @"lichanghong";
BOOL isSucess = [session connectAndWaitTimeout:30]; //this is part of the synchronous API
if(isSucess){
//以下部分是订阅一个主题
[session subscribeToTopic:@"topic" atLevel:2 subscribeHandler:^(NSError *error, NSArray<NSNumber *> *gQoss){
if (error) {
NSLog(@"Subscription failed %@", error.localizedDescription);
} else {
NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
}
}];
}
//发送数据 this is part of the asynchronous API
[session publishAndWaitData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]
onTopic:@"topic"
retain:NO
qos:MQTTQosLevelAtLeastOnce];
//主动和服务端断开
[session disconnect];
//取消订阅主题
[session unsubscribeTopic:@"topic" unsubscribeHandler:^(NSError *error) {
}];
- (void)newMessage:(MQTTSession *)session data:(NSData *)data onTopic:(NSString *)topic qos:(MQTTQosLevel)qos retained:(BOOL)retained mid:(unsigned int)mid
{
NSLog(@"data=%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
// NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]);
}
4,服务端(php在ubuntu16.04环境下的服务器)
0)安装了composer管理php包
1)composer init创建包配置文件composer.json
发现composer太难配置,弃之。。。。
简单测试方法:
1,http://www.open-open.com/lib/view/open1384352514336.html
2,http://www.codes51.com/article/detail_2674947.html
任选其一,推荐第二个。
ubuntu安装mqtt的ppa方法:
https://launchpad.net/~mosquitto-dev/+archive/ubuntu/mosquitto-ppa
php的无法运行起来,在ubuntu16.04找不到mosquitto.so,解决方案:
sudo pecl install Mosquitto-alpha
and created mosquitto.ini in
/etc/php5/mods-available/mosquitto.ini
and add this code
extension=mosquitto.so