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

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

Open
xiaolei000129 opened this issue Feb 22, 2024 · 1 comment
Labels
question It is a question regarding the project

Comments

@xiaolei000129
Copy link

Describe your question

image

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
@xiaolei000129 xiaolei000129 added the question It is a question regarding the project label Feb 22, 2024
@jianzhichu
Copy link

有解决办法么。我也遇到了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question It is a question regarding the project
Projects
None yet
Development

No branches or pull requests

2 participants