最近在看mqtt的一些资料。结合项目也研究了一下。翻阅博客,大家对于ios开发mqtt到连接这一步就停止了。
关于cocoaMQTT的基础部分。
import UIKit
import CocoaMQTT
class ViewController: UIViewController {
var mqtt:CocoaMQTT?{
didSet{
if mqtt?.connState == CocoaMQTTConnState.connected {
//mqtt?.publish("chat", withString: "dtr")
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.mqtt?.publish("chat", withString: "我好开心啊", qos: CocoaMQTTQOS.qos0, retained: false, dup: false)
}
override func viewDidLoad() {
super.viewDidLoad()
let clientID = "CocoaMQTT1-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 1883)
mqtt?.username = "thinkpad"
mqtt?.password = "public"
// mqtt?.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
// mqtt?.publish("chat", withString: "dtet", qos: CocoaMQTTQOS.qos0, retained: true, dup: true)
mqtt?.keepAlive = 60
mqtt?.delegate = self
mqtt?.subscribe("chat")
mqtt?.connect()
}
}
extension ViewController:CocoaMQTTDelegate{
func mqttDidPing(_ mqtt: CocoaMQTT) {
}
func mqttDidReceivePong(_ mqtt: CocoaMQTT) {
}
func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
}
func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
//注意一定要连接成功了之后,才能发布主题和订阅主题。
if ack.description == "accept" {
mqtt.publish("chat", withString: "dtr")
mqtt.subscribe("chht")
}
}
func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
print(message.string ?? "999")
}
func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
}
func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
}
func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topic: String) {
}
func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String) {
}
}
其实在写这些代码的时候,我发现了。订阅主题,发布主题,必须要等到连接成功之后才能进行。当然这篇博客还是会继续的写下去的。真正的项目开发,不只有这样,包括多线程的处理消息的接收。连接设备.订阅多个主题。SSL连接。等等。
版权声明:本文为qq_31927785原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。