dotnet / dotnet/MQTTnet

WebSocket .NET 5.0 connection and publish issues

Open
#1,197 7 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

### Describe your question
There are issues with Managed client and WebSockets, it fails (or takes a long time more than 30-60 secs) to connect and publish to a test Mosquitto broker, with .NET 5.0 on Windows 10, and fails on Mac OS X. It does work sometimes if .NET standard framework or Mono is used on Mac OS X or Linux.

I suspect platform specific code issues with the ManagedClient code (messages getting enqueued without actually being published, Task completion or threading issues?). The examples for ManagedClient here: https://dzone.com/articles/mqtt-publishing-and-subscribing-messages-to-mqtt-b and https://github.com/chkr1011/MQTTnet/wiki/ManagedClient were having these issues with dotnet core.

I managed to get the code working only using a Task completion and Task.ContinueWith() approach as shown here (@chkr1011 is this an optimal approach?):

```c#
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

var mqttClient = new MqttFactory().CreateMqttClient();
var managedClient = new ManagedMqttClient(mqttClient, new MqttNetLogger());

try
{
var task = Task.Run(async () =>
{
var connected = GetConnectedTask(managedClient);
await ConnectMQTTAsync(managedClient, token, m_MQTTUrl, m_MQTTclientId, m_MQTTuser, m_MQTTpassw);
await connected;

});

task.ContinueWith(antecedent => {
if (antecedent.Status == TaskStatus.RanToCompletion)
{
Task.Run(async () =>
{
await PublishMQTTAsync(managedClient, token, m_MQTTtopic, serializedJSON);
await managedClient.StopAsync();
});
}
});

}

catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}

```
```c#
public static async Task ConnectMQTTAsync(ManagedMqttClient mqttClient, CancellationToken token, string mqtturl, string clientId, string mqttuser, string mqttpassw)
{
bool mqttSecure = true;

var messageBuilder = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithCredentials(mqttuser, mqttpassw)
.WithCommunicationTimeout(new TimeSpan(0, 0, 5))
.WithKeepAlivePeriod(TimeSpan.FromSeconds(1200))
.WithWebSocketServer(mqtturl)
.WithCleanSession();

var options = mqttSecure
? messageBuilder
.WithTls()
.Build()
: messageBuilder
.Build();

var managedOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(options)
.Build();

await mqttClient.StartAsync(managedOptions);

}

Task GetConnectedTask(ManagedMqttClient managedClient)
{
TaskCompletionSource connected = new TaskCompletionSource();
managedClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
{
managedClient.ConnectedHandler = null;
connected.SetResult(true);
});
return connected.Task;
}

public static async Task PublishMQTTAsync(ManagedMqttClient mqttClient, CancellationToken token, string topic, string payload, bool retainFlag = true, int qos = 1)
{
if (mqttClient.IsConnected)
{
await mqttClient.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qos)
.WithRetainFlag(retainFlag)
.Build(), token);
}
}

```

### Which project is your question related to?

- ManagedClient

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.