emqx / CocoaMQTT

MQTT 5.0 client library for iOS and macOS written in Swift
https://www.emqx.com/en
Other
1.59k stars 418 forks source link

How to connect without specifying port number? #439

Closed laus102 closed 2 years ago

laus102 commented 2 years ago

Hello,

I am trying to use CocoaMQTT to connect given a wss url of the following format:

wss://abcdefg-ats.iot.eu-west-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AMZ_CREDENTIAL&X-Amz-Date=20220207T193728Z&X-Amz-Expires=0&X-Amz-SignedHeaders=host&X-Amz-Signature=123456

The formation of the URL is out of my control, and I have to use the URL in the way it is given.

I notice in the library, there is no way to not specify a port number, with the initializers that are readily available.

I asked the supplier of the wss url and they said specifying the port number will make the connection impossible.

Here is some example code of what I am doing:

        let socket = CocoaMQTTWebSocket(uri: "wss://abcdefg-ats.iot.eu-west-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AMZ_CREDENTIAL&X-Amz-Date=20220207T193728Z&X-Amz-Expires=0&X-Amz-SignedHeaders=host&X-Amz-Signature=123456")

        socket.enableSSL = true
        mqtt = CocoaMQTT(clientID: "1234", host: "abcdefg-ats.iot.eu-west-1.amazonaws.com", port: 443, socket: socket)
        ...
       let result = mqtt.connect(timeout: 30)

Is there some way to bypass supplying a port number?

laus102 commented 2 years ago

For reference, when I modify CocoaMQTTWebSocket.swift to this, it works:

    public func connect(toHost host: String, onPort port: UInt16, withTimeout timeout: TimeInterval) throws {

//        let urlStr = "\(enableSSL ? "wss": "ws")://\(host):\(port)\(uri)"
        let urlStr = "\(uri)"

        guard let url = URL(string: urlStr) else { throw CocoaMQTTError.invalidURL }
        try internalQueue.sync {
            connection?.disconnect()
            connection?.delegate = nil
            let newConnection = try builder.buildConnection(forURL: url, withHeaders: self.headers)
            connection = newConnection
            newConnection.delegate = self
            newConnection.queue = internalQueue
            newConnection.connect()
        }
    }
leeway1208 commented 2 years ago

@laus102 Thanks for your support. I will fix it to provide this scenario ASAP.

laus102 commented 2 years ago

@leeway1208 take a look at the PR #440, that may be helpful!

leeway1208 commented 2 years ago

@laus102 you are absolutely right. Thank you!