dotnet / dotnet/MQTTnet

链接频繁断开【异常断线触发重连】错误信息:Not allowed to connect while connect/disconnect is pending.

Open
#1,934 4 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

![image](https://github.com/dotnet/MQTTnet/assets/44334120/1ea753c9-1f4d-4851-8a89-291d16fb6a0a)

public async Task StartAsync()
{
var url = _configuration["MqttStrings:Url"];
if (!TryParse(_configuration["MqttStrings:Port"], out int port) || string.IsNullOrWhiteSpace(url)) return;
var clientId = $"{_configuration["MqttStrings:ClientId"] ?? "IotServerClient"}_{new Random().Next(0, 9999)}";
_logger.LogInformation($"ClientId:{clientId}");
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer(url, port)
.WithClientId(clientId)
.Build();

await _mqttClient.ConnectAsync(mqttClientOptions);
ApplicationMessageReceived();
await SubscribeAsync();
Heartbeat(mqttClientOptions);
}

private void Heartbeat(MqttClientOptions mqttClientOptions)
{
_ = Task.Run(
async () =>
{
while (true)
{
try
{
if (await _mqttClient.TryPingAsync()) continue;

await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
ApplicationMessageReceived();
await SubscribeAsync();
}
catch (Exception ex)
{
_logger.LogError($"【异常断线触发重连】错误信息:{ex.Message}");
}
finally
{
// 每15秒检查一次连接状态,如果需要,执行一次重新连接。
await Task.Delay(TimeSpan.FromSeconds(15));
}
}
});
}
private void ApplicationMessageReceived()
{
var semaphore = new SemaphoreSlim(80);
_mqttClient.ApplicationMessageReceivedAsync += async arg =>
{
await semaphore.WaitAsync();
_ = Task.Run(async () =>
{
.........
}).ConfigureAwait(false);
return;
};
}

public async Task SubscribeAsync()
{
.......
}

以上是我的链接代码。

### Which project is your question related to?

- Client
- ManagedClient
- Server
- Generic

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.