Mqtt协议IOS端移植3

ServerMqFramework.h

#import "MqttFramework.h"

@interface ServerMqFramework : MqttFramework


/**
 * @brief  得到模块控制器的句柄单例
 *
 * @param [in] N/A
 * @param [out] N/A
 * @return void
 * @note
 */

+(ServerMqFramework*)getMQttServerFrameInstance;

- (int)callBusinessProcessEX:(NSString *)capabilityId withMessageType:(NSString *)MessageType WithMessage:(id)messageVector withTopic:(NSString *)topic;

@end


ServerMqFramework.m


#import "ServerMqFramework.h"
#import "getMacAddress.h"

@implementation ServerMqFramework



/**
 * @brief  得到模块控制器的句柄单例
 *
 * @param [in] N/A
 * @param [out] N/A
 * @return void
 * @note
 */

static ServerMqFramework *mqttInstance = nil;
+(ServerMqFramework*)getMQttServerFrameInstance
{
    @synchronized(self)
	{
		if(mqttInstance==nil)
		{
			mqttInstance=[[self alloc]init];
        }
	}
	return mqttInstance;
}


#pragma  --mark  BusinessModuleProtocol  delegate
- (int)initBusinessModule:(BusinessModuleInfo*)info
{
    
    info.businessModuleIdEX = @"MqttServerFrameWork";//
    businessFrameworks_ = info.businessFramework;
    return 0;
}


//指定发送到远程的响应接收者的主题   (实现宏观上的点对点传输)  //2012/11/30   modify

- (int)callBusinessProcessEX:(NSString *)capabilityId withMessageType:(NSString *)MessageType WithMessage:(id)messageVector withTopic:(NSString *)topic
{
    NSLog(@"server capabilityId = %@  topic = %@  messageVector = %@",capabilityId,MessageType,messageVector);
    
    AppDelegate  *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
	MQTTClient   *serverMQTTClient = [app serverMqClient];
    
    
   
    
    NSString  *sendStr = [[NSString alloc] initWithData:[XmlAdept makeMqttXML:MessageType withDictionary:(NSDictionary *)messageVector] encoding:NSUTF8StringEncoding];
    
    //    /****************去掉最后换行符********************/
    int index = sendStr.length-1;
    sendStr = [sendStr substringToIndex:index];
    
    NSString *string = [NSString stringWithFormat:@"**%@**",sendStr];
    NSLog(@"server senderMesg = %@",string);
    [serverMQTTClient publishString:sendStr toTopic:topic retain:NO];
    
    return 0;
}

-(void)requestResult:(NSString *)topic  withData:(id)resultData
{
    NSLog(@"远程mq服务器发送业务广播 给监听者");
    [businessFrameworks_ broadcastBusinessNotifyEX:topic withInParam:resultData];
}



/**
 * @brief 定义mqtt消息主题
 *
 * @param [in] N/A
 * @param [out] N/A
 * @return void
 * @note
 */

-(void)productTheme:(NSString *)theme
{
    
    NSLog(@"server theme = %@",theme);
    AppDelegate  *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    MQTTClient *mosq = [app serverMqClient];

    [mosq setHost:Mqtt_Server_URL];
      
    [mosq connect];
    [mosq subscribe:theme];
}

/**
 * @brief 重连mqtt服务器
 *
 * @param [in] N/A
 * @param [out] N/A
 * @return void
 * @note
 */
-(void)reconnectMqtt
{
    AppDelegate  *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    MQTTClient *mosq = [app serverMqClient];
   
    [mosq setHost:Mqtt_Server_URL];
    
    [mosq reconnect];
    
}

#pragma --mark  mosquittoclientDelegate

- (void) didConnect:(NSUInteger)code
{
    if (code == 0)
    {
        NSLog(@"连接远程Mqtt服务器返回码为:%d 连接mqtt成功",code);
    }
    else
    {
        NSLog(@"连接远程Mqtt服务器失败");
    }
    
	
}

- (void) didDisconnect
{
	NSLog(@"Server mqtt disconnect!");
    AppDelegate  *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    MQTTClient *mosq = [app serverMqClient];
    //断开后自动重连
    //3g或wifi任一可达就重连
    if ([Common IsEnable3G] || [Common IsEnableWIFI])
    {
        [mosq reconnect];   //远程MQTT服务器端重连
        NSString  *serverTheme = getMacAddress();
        [mosq subscribe:serverTheme]; //重新订阅主题
    }
    
}

//处理各个主题对应的message

- (void) didReceiveMessage: (NSString*)message topic:(NSString*)topic
{
	NSLog(@" serverMqtt %@ => %@", topic, message);
  
    NSArray   *resultArr = [[NSArray alloc]initWithObjects:message, nil];
    NSArray   *list = [XmlAdept mqttParseMessageNode:resultArr];
    NSString  *type = [[list objectAtIndex:0] objectForKey:@"type"];
    
    [self requestResult:type withData:list];
    
    
	
}

/**
 * @brief 给远程mqtt服务器发送消息   对外接口
 *
 * @param [in] N/A
 * @param [out] N/A
 * @return void
 * @note
 */

+(void)publishMessage:(NSString *)message   withTopicType:(NSString *)topicType
{
    AppDelegate  *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
	MQTTClient *mosq = [app serverMqClient];
    [mosq publishString:message toTopic:topicType retain:NO];  //消息的retain类型设置为NO让其不在消息缓冲池中保留
}

-(void)dealloc
{
    [super dealloc];
}


@end


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
MQTT是一种轻量级的消息传输协议,常用于物联网设备之间的通信。MQTT服务器的实现可以使用多种语言和框架,这里以使用Node.js和Mosca框架为例进行介绍。 Mosca是基于Node.js的MQTT服务器框架,支持多种协议版本和QoS等级。以下是Mosca的服务器实现步骤: 1. 安装Mosca框架和相关依赖 ``` npm install mosca bunyan --save ``` 2. 创建一个MQTT服务器实例 ```javascript var mosca = require('mosca'); var settings = { port: 1883 // MQTT服务器监听的口号 }; var server = new mosca.Server(settings); ``` 3. 监听MQTT客户连接事件 ```javascript server.on('clientConnected', function(client) { console.log('Client connected: ', client.id); }); ``` 4. 监听MQTT客户发布消息事件 ```javascript server.on('published', function(packet, client) { console.log('Published:', packet.payload.toString()); }); ``` 5. 监听MQTT客户订阅事件 ```javascript server.on('subscribed', function(topic, client) { console.log('Client subscribed to:', topic); }); ``` 6. 监听MQTT客户取消订阅事件 ```javascript server.on('unsubscribed', function(topic, client) { console.log('Client unsubscribed from:', topic); }); ``` 7. 监听MQTT客户断开连接事件 ```javascript server.on('clientDisconnected', function(client) { console.log('Client disconnected:', client.id); }); ``` 以上是Mosca框架的基本使用方法,可以根据需要自定义添加其他事件监听器。 除了Mosca框架外,还有其他MQTT服务器的实现方式,例如使用Java语言编写的Eclipse Mosquitto和使用Go语言编写的Eclipse Paho等。不同的实现方式可能有所不同,但基本原理都是类似的。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值