当前位置:首页>科技>正文

mqtt适合设备向服务器上报数据吗 怎么将消息发送到mqtt代理服务器

2023-04-24 20:29:32 互联网 未知 科技

 mqtt适合设备向服务器上报数据吗 怎么将消息发送到mqtt代理服务器

mqtt适合设备向服务器上报数据吗

可以的
MQTT协议是为大量计算能力有限,且工作在低带宽、不可靠的网络的远程传感器和控制设备通讯而设计的协议,国内很多企业都广泛使用MQTT作为Android手机客户端与服务器端推送消息的协议.

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

通过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有很好地理解。

ubuntu mqtt 服务怎么搭建

在Ubuntu下搭建MQTT服务器",主要涉及到【MQTT】在Ubuntu下搭建MQTT服务器方面的内容,对于【MQTT】在Ubuntu下搭建MQTT服务器感兴趣的同学可以参考一下。