Cocoa MQTT - 由远程对等体关闭的套接字

时间:2018-03-30 17:22:23

标签: ios xcode swift4 mqtt mosquitto

当我尝试使用CocoaMQTT连接到我的服务器时,我遇到了重大问题。我正在运行一个带有Mosquitto代理的Ubuntu服务器。

我已按照所有指示进行操作,但仍无法找到解决方案。

我使用过标准的Cocoa连接功能。

import json

write_file = "/path/to/output.json"
holder_dictionary = predictions.to_dict(orient='records')

with open(write_file, 'w') as outfile:
    json.dump(holder_dictionary, outfile)

然后在viewDidLoad

中调用此代码
private func createMQTTConnection() {
    let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
    mqtt = CocoaMQTT(clientID: clientID, host: "xxx.xx.xx.x", port: 1883)
    mqtt!.username = "root"
    mqtt!.password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    //mqtt.willMessage = CocoaMQTTWill(topic: "pi/pir", message: "dieout")
    mqtt!.keepAlive = 60
    mqtt!.delegate = self
    mqtt!.allowUntrustCACertificate = true
    mqtt!.connect()

我拥有所有其他标准的cocoaMQTT项目

verride func viewDidLoad() {

    super.viewDidLoad()
    //establishes a connection 
    createMQTTConnection()
     // creates a message 
     mqtt!.publish("pi/pir", withString: "Iphone Connected")
    // Do any additional setup after loading the view.
}

然后我收到以下错误;

didPublishMessage:和2 mqttDidDisconnect:由远程对等方关闭的套接字

非常感谢任何帮助。 谢谢

1 个答案:

答案 0 :(得分:0)

拨打connect是异步通话,您可能在调用发布时无法连接。尝试将publish移至didConnect委托方法。

func mqtt(_ mqtt: CocoaMQTT, didConnect host: String, port: Int) {
    print("mqtt did connect to \(host):\(port)")
    mqtt.publish("pi/pir", withString: "Iphone Connected")
}

日志:

mqtt did connect to 192.168.1.104:1883 
didPublishMessage: <CocoaMQTT.CocoaMQTTMessage: 0x1c0674100> and 2