sroebert / mqtt-nio

Non-blocking, event-driven Swift client for MQTT (3.1.1 and 5.0).
MIT License
54 stars 13 forks source link

ioOnClosedChannel error when connecting #4

Closed azzastudios closed 2 years ago

azzastudios commented 2 years ago

I am trying to connect to a broker on a watch app (WatchOS: 8.3) but I receive this error: Error while connecting ioOnClosedChannel

I have been looking trough the package to find something but I can't seem to find anything.

This is the code I use (with correct values for username, password and url filled in):

    let credentials = MQTTConfiguration.Credentials.init(username: "username", password: "password")

    let client = MQTTClient(configuration: .init(url: URL(string: "url")!, credentials: credentials))
    //client.connect()
    client.connect().whenComplete { result in
        switch result {
        case .success:
            print("Succesfully connected")
        case .failure(let error):
            print("Error while connecting \(error)")
        }
    }

Thanks in advance!

sroebert commented 2 years ago

If the channel was closed, it might be because the server did not accept the credentials or MQTT version.

By default the client uses MQTT version 5, you might want to set that to 3 in the configuration to check if that works. Depending on the broker, it might not support v5. (protocolVersion: .version3_1_1)

azzastudios commented 2 years ago

Thanks for your response.

I've tried this, but I'm getting the same error. Could there be another reason?

I assume there is something else wrong because I have the same issue with the test broker of mosquitto:

   let client = MQTTClient(configuration: .init(url: URL(string: "wss://test.mosquitto.org:8081")!))

    client.connect().whenComplete { result in
        switch result {
        case .success:
            print("Succesfully connected")
        case .failure(let error):
            print("Error while connecting \(error)")
        }
    }
sroebert commented 2 years ago

I am seeing this exact error if the MQTTClient gets deallocated, are you keeping a reference to the client after connecting?

In any case I will have a look at giving a more appropriate error when disconnecting because of client deallocation.

azzastudios commented 2 years ago

Yes, that was the issue. I was creating the reference in a function so it did get deallocated.

Thank you very much!