链接频繁断开【异常断线触发重连】错误信息:Not allowed to connect while connect/disconnect is pending.
- Dominant language
- C#
- Stars
- 5.1k
- Forks
- 1.2k
- PR merge metrics
- No merged PRs in 30d
Description
### Describe your question

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.