怎么将消息发送到mqtt代理服务器

 我来答
就烦条0o
2016-05-28 · 知道合伙人软件行家
就烦条0o
知道合伙人软件行家
采纳数:33315 获赞数:46501
从事多年系统运维,喜欢编写各种小程序和脚本。

向TA提问 私信TA
展开全部
通过Cocoa Pods添加MQTTKit

MQTTKit在github上链接https://github.com/NormanLeeIOS/MQTTKit#send-a-message,down下来。

cd到工程目录,输入pod install,用xcode打开工程的打开xcworkspace扩展名的文件。

如果不是MQTTKit存在更新的版本,则输入pod update。

新建一个MQTT的服务请求

NSString *clientID = ...
MQTTClient *client = [[MQTTClient alloc] initWithClientId:clientID];

发送消息,每次发送消息包括目标host和本地MQTT消息.具体MQTT格式消息见代码。这里Host可以是Server的IP,不需要host表解析。

// connect to the MQTT server
[self.client connectToHost:@"iot.eclipse.org"
completionHandler:^(NSUInteger code) {
if (code == ConnectionAccepted) {
// when the client is connected, send a MQTT message
[self.client publishString:@"Hello, MQTT"
toTopic:@"/MQTTKit/example"
withQos:AtMostOnce
retain:NO
completionHandler:^(int mid) {
NSLog(@"message has been delivered");
}];
}
}];

订阅主题并接受MQTT格式的消息,这部分在viewdidload中实现。

// define the handler that will be called when MQTT messages are received by the client
[self.client setMessageHandler:^(MQTTMessage *message) {
NSString *text = [message.payloadString];
NSLog(@"received message %@", text);
}];

// connect the MQTT client
[self.client connectToHost:@"iot.eclipse.org"
completionHandler:^(MQTTConnectionReturnCode code) {
if (code == ConnectionAccepted) {
// when the client is connected, subscribe to the topic to receive message.
[self.client subscribe:@"/MQTTKit/example"
withCompletionHandler:nil];
}
}];

断开连接

[self.client disconnectWithCompletionHandler:^(NSUInteger code) {
// The client is disconnected when this completion handler is called
NSLog(@"MQTT client is disconnected");
}];

整个连接建立、发送消息、接受消息、断开连接都是通过Block的消息机制来实现,因此需要对block有很好地理解。
ipipgo
2023-11-29 广告
作为南京光年之内网络科技有限公司的工作人员,我可以回答跨境电商代理IP的问题。代理IP可以帮助突破IP访问限制,提高网络访问速度和稳定性,同时还能保护用户的隐私和安全。我们公司提供的代理IP服务具有高速、稳定、安全、灵活的特点,能够帮助用户... 点击进入详情页
本回答由ipipgo提供
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式