如何使用swift通过wss连接到MQTT?

时间:2017-12-07 16:32:26

标签: swift mqtt

我正在使用CocoaMQTT并尝试使用以下代码连接到MQTT服务:

    let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
    //This is myHost: wss://myserver.test:9001
    let mqtt = CocoaMQTT(clie.ntID: clientID, host: "myserver.test", port: 9001)
    mqtt.keepAlive = 10000
    mqtt.username = "username"
    mqtt.password = "password"
    mqtt.enableSSL = true
    mqtt.delegate = self
    mqtt.connect()
    mqtt.autoReconnect = true

我收到错误:Error Domain = GCDAsyncSocketErrorDomain Code = 7“Socket由远程对等方关闭”UserInfo = {NSLocalizedDescription = Socket由远程对等方关闭}

CocoaMQTT是支持wss还是仅支持tcp?如果它不支持,是否还有其他swift客户端?

1 个答案:

答案 0 :(得分:0)

这是CocoaMQTT的一个例子。也许有帮助。

    let clientID = "CocoaMQTT-\(animal!)-" + String(ProcessInfo().processIdentifier)
    mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 8883)
    mqtt!.username = ""
    mqtt!.password = ""
    mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
    mqtt!.keepAlive = 60
    mqtt!.delegate = self
    mqtt!.enableSSL = true

    let clientCertArray = getClientCertFromP12File(certName: "client-keycert", certPassword: "MySecretPassword")

    var sslSettings: [String: NSObject] = [:]
    sslSettings[GCDAsyncSocketManuallyEvaluateTrust as String] = NSNumber(value: true)
    sslSettings[kCFStreamSSLCertificates as String] = clientCertArray

    mqtt!.sslSettings = sslSettings