C#。如何在一个程序中连接2个mqtt-broker?

问题描述 投票:0回答:1

我正在尝试使用 C# 在一个程序中使用 2 个 MQTT 代理
我正在使用“M2MQTT.Net”库在我的程序中使用 MQTT 应用程序。

首先,我成功与broker建立了单个MQTT连接。
另外,成功订阅和发布主题。

// Simple code that i make single connection with broker.
private void InitMqtt()
    {
        MqttClient = new MqttClient(brokerAddr);
    }

// MqttClinet() method in the M2MQTT.Net library, MQTTClient class.
public MqttClient(string brokerHostName)
        : this(brokerHostName, 1883, secure: false, null, null, MqttSslProtocols.None)
    {
    }

那么如果我想要建立超过 1 个 MQTT 连接怎么办,这是正确的代码吗?

private void InitMqtt()
    {
        MqttClient = new MqttClient(brokerAddr);
        MqttClient2 = new MqttClient(brokerAddr2);
        MqttClient3 = new MqttClient(brokerAddr3);
    }

如果可以与各种mqtt代理进行多重连接,
我可以分别处理 3 个经纪人的事件吗?
谢谢阅读。问候。

c# mqtt
1个回答
0
投票

可以在单个任务中将多个客户端连接到多个代理,但每个 Mqtt 客户端都有自己的回调方法。像这样的事情:

    protected MyMqttClient(string name ,MqttClientOptions options, List<string> TopicFiletrs)
    {
        //this._name = $"{GetType().Name}({name})";
        this._name = name;
        var factory = new MqttFactory();
        _client = factory.CreateMqttClient();
        
        _client.ApplicationMessageReceivedAsync += _client_ApplicationMessageReceivedAsync;
        _client.ConnectedAsync += _client_ConnectedAsync;
        _client.DisconnectedAsync += _client_DisconnectedAsync;

        _options = options;
        _TopicFiletrs = TopicFiletrs;
        
    }
© www.soinside.com 2019 - 2024. All rights reserved.