Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object #733

Closed
det-iot opened this issue Aug 1, 2019 · 14 comments
Closed
Labels
feature-request New feature or request support Support is needed

Comments

@det-iot
Copy link

det-iot commented Aug 1, 2019

Hello,

I have a task with a parallel.ForEach ( I have also tried with a simple foreach)

Parallel.ForEach(receiveMessageResponse.Messages, message =>
{
    if (!string.IsNullOrEmpty(message.Body))
    {
        try
        {
            mqtt.ManageMQTTClient(MQTTconfigPublisher, message.Body).GetAwaiter().GetResult();
        }
        catch (Exception e)
        {
            parallelExceptions.Enqueue(e);
        }
    }
});

And when I run the app I have the following error:

MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
at AmpliaControlSystem.MQTT.ManageMQTTClient(MQTTConfiguration MQTTconfigPublisher, String payload) in /app/MQTT.cs:line 38

As a note, this happened to me in local, but I re-write the code from the beggining and it was fixed. Now I'm trying to deploy to AWS and the error happen again

The task ManageMQTTClient which produce the error:

public async Task ManageMQTTClient( MQTTConfiguration MQTTconfigPublisher, string payload)
{
    string topic = payload.Split(";")[1];
    string cliente =  Guid.NewGuid().ToString();
    try
    {
        IMqttClientOptions optionsPublisher = new MqttClientOptionsBuilder()
                    .WithTcpServer(MQTTconfigPublisher.Servidor)
                    .WithClientId(cliente)
                    .WithCredentials(MQTTconfigPublisher.Username, MQTTconfigPublisher.Password)
                    .WithCleanSession(false)
                    .WithKeepAlivePeriod(System.TimeSpan.FromSeconds(60))
                    .Build();

        IMqttClient mqttClientPublisher = new MqttFactory().CreateMqttClient();


        await mqttClientPublisher.ConnectAsync(optionsPublisher);
     
        if (mqttClientPublisher.IsConnected)
        {
            try
            {
                await mqttClientPublisher.PublishAsync(topic, payload.Split(";")[2], MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error en 1" + ex);
                throw;
            }
        }
        //await mqttClientPublisher.DisconnectAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error en 2" + ex);
        throw;
    }
}

The line 38 in the original code (here I have deleted the comments) is:

await mqttClientPublisher.ConnectAsync(optionsPublisher);

I'm using NuGet MQTTnet 3.0.5 and Net Core 2.1

Which project is your bug related to?

  • Client
@SeppPenner
Copy link
Collaborator

For me, this seems quite similar to #728 (But it's not a duplicate).

@SeppPenner SeppPenner added the support Support is needed label Aug 2, 2019
@det-iot
Copy link
Author

det-iot commented Aug 2, 2019

Finally, I got what was wrong.

I was trying to access lo local broker (local ip) from the outside.

The problem here was the exception messages didn't say anything about the connection was no able to be establish.

Should the error message say something about that?

@SeppPenner SeppPenner added the feature-request New feature or request label Aug 2, 2019
@SeppPenner
Copy link
Collaborator

Should the error message say something about that?

If you ask me, yes. I'm not in the implementation details (yet), so @chkr1011 needs to answer this as well.

@erikkj
Copy link

erikkj commented Aug 21, 2019

I have a similar issue in my code. I am using ManagedClient with reconnect delay = 10 seconds. Sporadic in my logs i see exceptions like this when the client disconnects:

2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)

The client is able to reconnect to the server most of the times, but sometimes the client "dies" and does not run anymore. The last log message from MQTTClient in my log when this happens is this:

2019-08-20 17:06:27.736 +00:00 [ERR] >> [2019-08-20T17:06:27.7217443Z] [174] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Connection refused []:8883 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: Connection refused []:8883
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
   at System.Net.Sockets.Socket.MultipleAddressConnectCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:33.405 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:33.407 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:37.734 +00:00 [DBG] >> [2019-08-20T17:06:37.7338579Z] [123] [MqttClient] [Verbose]: Trying to connect with server 'URL' (Timeout=00:00:10).
2019-08-20 17:06:43.404 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:43.411 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:47.755 +00:00 [DBG] >> [2019-08-20T17:06:47.7552332Z] [187] [MqttClient] [Verbose]: Disconnecting [Timeout=00:00:10]

@xxGL1TCHxx
Copy link

I have a similar issue in my code. I am using ManagedClient with reconnect delay = 10 seconds. Sporadic in my logs i see exceptions like this when the client disconnects:

2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)

The client is able to reconnect to the server most of the times, but sometimes the client "dies" and does not run anymore. The last log message from MQTTClient in my log when this happens is this:

2019-08-20 17:06:27.736 +00:00 [ERR] >> [2019-08-20T17:06:27.7217443Z] [174] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Connection refused []:8883 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: Connection refused []:8883
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
   at System.Net.Sockets.Socket.MultipleAddressConnectCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:33.405 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:33.407 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:37.734 +00:00 [DBG] >> [2019-08-20T17:06:37.7338579Z] [123] [MqttClient] [Verbose]: Trying to connect with server 'URL' (Timeout=00:00:10).
2019-08-20 17:06:43.404 +00:00 [DBG] Starting HttpMessageHandler cleanup cycle with 1 items
2019-08-20 17:06:43.411 +00:00 [DBG] Ending HttpMessageHandler cleanup cycle after 0.0099ms - processed: 0 items - remaining: 1 items
2019-08-20 17:06:47.753 +00:00 [ERR] >> [2019-08-20T17:06:47.7478776Z] [187] [MqttClient] [Error]: Error while connecting with server.
MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
   at MQTTnet.Internal.MqttTaskTimeout.WaitAsync(Func`2 action, TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
   at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
2019-08-20 17:06:47.755 +00:00 [DBG] >> [2019-08-20T17:06:47.7552332Z] [187] [MqttClient] [Verbose]: Disconnecting [Timeout=00:00:10]

FWIW, I'm having the same exact issue as Erikkj. I have had several instances over the past few weeks where the client throws this exception and continues to fail to reconnect. Restarting the application clears it up. Sorry if this is a separate issue, I just ran across it while trying to Google my problem.

@stedaho
Copy link

stedaho commented Sep 30, 2019

I can confirm that this issue occurs occasionally on my test system, too. For the case it helps: I noticed that I never see a "OnDisconnected" event before the re-connecting fails.

MQTTnet v3.0.8, .NET Core 3.0, Linux on ARM32.

@alexey-grebennikov
Copy link

I have the same issue.
MQTTnet v3.0.8, .NET Core 2.1, Windows Server

@ps-weber
Copy link

ps-weber commented Oct 23, 2019

I have a similar issue where I get a ObjectDisposedExcpetion wrapped in a MqttCommunicationException when the connection to the server times out while running MqttClient.ConnectAsync(). I traced it back to this snippet in MqttTcpCannel.cs:

// Workaround for: workaround for https://github.com/dotnet/corefx/issues/24430
using (cancellationToken.Register(() => socket.Dispose()))
{
#if NET452 || NET461
    await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, _options.Server, _options.GetPort(), null).ConfigureAwait(false);
#else
    await socket.ConnectAsync(_options.Server, _options.GetPort()).ConfigureAwait(false);
#endif
}

I would suggest catching the ObjectDisposedExcpetion and hiding the workaround to library users, since ObjectDisposedExcpetion sounds like an implementation error rather than a simple timeout.

@Feyb
Copy link

Feyb commented Dec 17, 2019

also getting this even with the new MQTTnet 3.0.9-rc1, but its usually in a combination with a timeout. It does reconnect then i get like 2-3 messages, the same happens again and so on until the client dies.

> 2019-12-17 02:33:21.026 +00:00	[wrn]	Timeout while waiting for packet of type 'MqttPingRespPacket'.	[MQTTnet.MqttClient]
> 2019-12-17 02:33:21.031 +00:00	[wrn]	Communication error while sending/receiving keep alive packets.	[MQTTnet.MqttClient]
> MQTTnet.Exceptions.MqttCommunicationTimedOutException: Exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' was thrown.
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.PacketDispatcher.MqttPacketAwaiter`1.<WaitOneAsync>d__4.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<SendAndReceiveAsync>d__46`1.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<TrySendKeepAliveMessagesAsync>d__47.MoveNext()
> 2019-12-17 02:33:21.423 +00:00	[wrn]	Disconnected	[.....Services.MqttClient]
> 2019-12-17 02:33:21.426 +00:00	[wrn]	Communication error while receiving packets.	[MQTTnet.MqttClient]
> MQTTnet.Exceptions.MqttCommunicationException: Cannot access a disposed object.
> Object name: 'System.Net.Sockets.NetworkStream'. ---> System.ObjectDisposedException: Cannot access a disposed object.
> Object name: 'System.Net.Sockets.NetworkStream'.
>    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
>    at System.IO.Stream.<>c.<BeginEndReadAsync>b__43_1(Stream stream, IAsyncResult asyncResult)
>    at System.Threading.Tasks.TaskFactory`1.FromAsyncTrimPromise`1.Complete(TInstance thisRef, Func`3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization)
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Implementations.MqttTcpChannel.<ReadAsync>d__17.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Formatter.MqttPacketReader.<ReadFixedHeaderAsync>d__3.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceiveAsync>d__37.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceivePacketAsync>d__35.MoveNext()
>    --- End of inner exception stack trace ---
>    at MQTTnet.Adapter.MqttChannelAdapter.WrapException(Exception exception)
>    at MQTTnet.Adapter.MqttChannelAdapter.<ReceivePacketAsync>d__35.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
>    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
>    at MQTTnet.Client.MqttClient.<TryReceivePacketsAsync>d__48.MoveNext()
> 2019-12-17 02:33:21.427 +00:00	[wrn]	Disconnected	[.....Services.MqttClient]

@andrei-m-code
Copy link

andrei-m-code commented Feb 11, 2020

@Feyb @JanEggers confirmed. we're getting same object disposed exception with 3.0.9-rc1`. Thoughts?

.NET Core 3.0, Windows 10

@JanEggers
Copy link
Contributor

@andrei-m-code I dont know if @chkr1011 created a new version that contains the fixes I did last year?

@chkr1011 can you please verify / do so?

@arsu-leo
Copy link

arsu-leo commented May 6, 2021

I'm expericing this same issue on v3.0.15
MQTTnet v3.0.15 + MQTTnet.AspNetCore v3.0.15 (Kestrel).

When I'm having it, it won't run until I reboot.
Log / Trace / Call stack:

2021/05/06T15:24:13.862: WebSocketServer:Start
Microsoft.AspNetCore.Server.Kestrel: Critical: Unable to start Kestrel.
2021/05/06T15:24:15.067: WebSocketServer:Start: Exception: Mqtt failed to start, check inner exception
2021/05/06T15:24:15.092: Stack trace:
[...]
2021/05/06T15:24:15.097: GLApp::Caused by:
2021/05/06T15:24:15.100: GLApp::AggregateException: One or more errors occurred. (Intento de acceso a un socket no permitido por sus permisos de acceso.)
2021/05/06T15:24:15.102: GLApp::Stack trace:
System.Net.Sockets.SocketException (10013): Intento de acceso a un socket no permitido por sus permisos de acceso.
2021/05/06T15:24:15.104: GLApp::Caused by:
2021/05/06T15:24:15.105: GLApp::SocketException: Intento de acceso a un socket no permitido por sus permisos de acceso.
2021/05/06T15:24:15.109: GLApp::Stack trace:    at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketConnectionListener.Bind()
   at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory.BindAsync(EndPoint endpoint, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass21_0`1.<<StartAsync>g__OnBind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindEndpointAsync(ListenOptions endpoint, AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions.BindAsync(AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.AnyIPListenOptions.BindAsync(AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.EndpointsStrategy.BindAsync(AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func`2 createBinding)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
2021/05/06T15:24:16.122: MessageHandler::TriggerMessageToSend: ObjectDisposedException: Cannot access a disposed object.
2021/05/06T11:57:16.122: Trace:    at MQTTnet.Internal.Disposable.ThrowIfDisposed()
   at MQTTnet.Server.MqttServer.PublishAsync(MqttApplicationMessage applicationMessage, CancellationToken cancellationToken)
   at MQTTnet.Server.MqttServerExtensions.PublishAsync(IMqttServer server, MqttApplicationMessage applicationMessage)
   at MqttServerWrapper.PublishMessage(MqttApplicationMessage msg)

The translation for the socket error in english (from spanish is: 10013: An attempt was made to access a socket in a way forbidden by its access permissions.

MqttServer calls both HandleServerStartedAsync and HandleServerStoppedAsync, which means I can't trust the started trigger to know if the Mqtt started successfully, as the stopped is called slightly after and later on it propagates to Krestel.

Krestel fail is hard to track if you want to run it on behind while you do other things, as the run task will keep going unless start fails, sigterm or crtl+c. This means you have to do some wait/timeout to ensure startup was success (I know this is on me but maybe someone gives some insight for me), I have not been able to find any good candidate for somehwat StartupFullySuccess event.

The ports I'm using currently are 9001 and 9002.
netstat -a doesn't show any process on them nor through TCPView

For now when this issue shows up the only solution I find is to reboot.
I will start using differnt ports to ensure nothing else hidden by the system on there.

Is there any way that the port will get locked somehow even if I close everyhing?

@chkr1011
Copy link
Collaborator

Please retest with version 4.0. You can also try to set the linger state and/or "ReuseAddress" in the server options

@MGMeters
Copy link

MGMeters commented Nov 1, 2023

I have an ASP Net Core 5.0 application hosted on the server. It was working well in production, but after some time, it crashed. When I tested the same code on my local, it was working fine, but any new build was getting the same issue. Can anyone help me here? do

Unhandled exception. MQTTnet.Exceptions.MqttCommunicationException: Error while connecting with host 'Host address Name'.
---> System.Net.Sockets.SocketException (11001): No such host is known.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at MQTTnet.Implementations.CrossPlatformSocket.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MQTTnet.Implementations.CrossPlatformSocket.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at MQTTnet.Implementations.MqttTcpChannel.ConnectAsync(CancellationToken cancellationToken)
at MQTTnet.Adapter.MqttChannelAdapter.ConnectAsync(CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken)
at MQTTnet.Client.MqttClient.ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken)
at Mqtt.Client.AspNetCore.Services.MqttClientService.StartAsync(CancellationToken cancellationToken) in C:\Project\MGMeter\MCA.Services\Services\MqttClientService.cs:line 152
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at MCAPlateform.Program.Main(String[] args) in C:\Project\MGMeter\project\Program.cs:line 45

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request New feature or request support Support is needed
Projects
None yet
Development

No branches or pull requests