dotnet / MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
MIT License
4.51k stars 1.07k forks source link

An existing connection was forcibly disconnected by an external host. #1049

Closed MrSonay closed 3 years ago

MrSonay commented 3 years ago

HI

My connection fails when connecting to the MQTT broker. This happens even though the code is pretty much copied from the example that has been provided on this site. The exception that I'm getting: MQTTnet.Exceptions.MqttCommunicationException: 'An existing connection was forcibly disconnected by an external host.'

Can you guys see what I'm doing wrong here? I'm using https://test.mosquitto.org/ as the broker to test it against. Here is the link: https://test.mosquitto.org/

I'm using MQTTnet version 3.0.13.

 // Create a new MQTT client.
                var factory = new MqttFactory();
                var mqttClient = factory.CreateMqttClient();

                // Load certificate
                var certificatePath = @"..\mosquitto.org.crt";

                // Create TLS based parameters.
                var tlsParameters = new MqttClientOptionsBuilderTlsParameters
                {
                    Certificates = new List<X509Certificate> { X509Certificate.CreateFromCertFile(certificatePath) },
                    IgnoreCertificateRevocationErrors = true,
                    IgnoreCertificateChainErrors = false,
                    AllowUntrustedCertificates = false,
                    //SslProtocol = System.Security.Authentication.SslProtocols.Tls12
                }; 

                // Create TCP based options using the builder.
                var connectOptions = new MqttClientOptionsBuilder()
                    .WithClientId("Client1")
                    .WithTcpServer("test.mosquitto.org", 8883)
                    .WithTls(tlsParameters)
                    //.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
                    .WithCleanSession()
                    .Build();

                var conResult = await mqttClient.ConnectAsync(connectOptions);
MrSonay commented 3 years ago

The problem has been fixed and the solution was to use UseTls = true in MqttClientOptionsBuilderTlsParameters - which I forgot.