相关文章推荐

后后言

在后后一篇 C# MQTT using MQTTnet 中,透過 ManagedMqttClient 可以递送下到 mosquitto 的訊息。
可即是,當我將 mosquitto 安裝在 Azure VM(20.121.35.xxx) 後,
啟動 mosquitto 服務後,從本機 Client 這卻連不下到它。

解決

Firewall 設定

必须在 Azure VM 中必须允許 1833 Port 連入,

1.在 Network security group 設定 Inbound port rules ,
允許 TCP 1883 允許連入。

2.在 OS 驱动器 Windows Defender Firewall 中的 Advanced settings 設定 Inbound Rules

設定 mosquitto 及測試

mosquitto 服務起動後,
可以在 Command 視窗中下 netstat -an | findstr 1883 來查看一下但若有著針對 1883 Port 在 LISTENING,
內容如下,

從上面圖可以發現,有著針對 1883 Port 在 LISTENING,
但它只允許本機实作,因為即是 127.0.0.1:1883
必須為 0.0.0.0:1883 才會允許遠端实作。

1.調整 mosquitto.conf
新增 listener 1883 ,並先允許非官方实作

1
2
3
4
5
# listener port-number [ip address/host name/unix socket path]
listener 1883

# ...
allow_anonymous true
  • 註:目后后為測試不同機器实作,請勿設定在即将正式環境
  • 重啟服務後,在 Command 視窗中下 netstat -an 就可以發現,
    已變成 0.0.0.0:1883

    2.改进 MQControlCenter 專案
    原本 MQControlCenter 專案 Server 固定為 localhost ,
    拿掉從 Command 視窗中讀取使用者的輸入值,
    並執行起來,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    using MQTTnet.Client;
    using MQTTnet.Extensions.ManagedClient;
    using MQTTnet;
    using System.Text.Json;
    using static System.Console;
    using System.Text;
    using MQTTnet.Packets;

    var _mqttClient = new MqttFactory().CreateManagedMqttClient();

    var clientId = "controlCenter";

    WriteLine("請輸入 MQTT Broker Server:");
    var server = ReadLine();
    if (string.IsNullOrWhiteSpace(server))
    {
    server = "localhost";
    }

    var builder = new MqttClientOptionsBuilder()
    .WithClientId(clientId)
    .WithTcpServer(server);

    var options = new ManagedMqttClientOptionsBuilder()
    .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
    .WithClientOptions(builder.Build())
    .Build();
    // Set up handlers
    _mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;
    _mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;
    _mqttClient.ConnectingFailedAsync += _mqttClient_ConnectingFailedAsync;
    _mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync;

    var topicFilters = new List<MqttTopicFilter> { new MqttTopicFilter { Topic= "home/temperature/#" } };
    await _mqttClient.SubscribeAsync(topicFilters);

    WriteLine($"{clientId} 連線下到 MQTT Broker ({server}) ....");
    await _mqttClient.StartAsync(options);
    WriteLine("Press any key to stop receive message ...");
    ReadKey();

    Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
    {
    WriteLine("Connected");
    return Task.CompletedTask;
    };
    Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
    {
    WriteLine("Disconnected");
    return Task.CompletedTask;
    };
    Task _mqttClient_ConnectingFailedAsync(ConnectingFailedEventArgs arg)
    {
    WriteLine("Connection failed check network or broker!");
    return Task.CompletedTask;
    }

    Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
    {
    var topic = arg?.ApplicationMessage?.Topic;
    var payloadText = Encoding.UTF8.GetString(
    arg?.ApplicationMessage?.Payload ?? Array.Empty<byte>());

    WriteLine($"Received: Topic:{topic}, Payload:{payloadText}");
    return Task.CompletedTask;
    }

    3. mosquitto_pub 發佈訊息

    1
    2
    3
    mosquitto_pub -t "home/temperature/sensor1" -m "hello world"
    mosquitto_pub -t "home/temperature/sensor2" -m "message from azure vm"
    mosquitto_pub -t "home/temperature/sensor3" -m "message from azure vm sensor3"

    4.最後在本機 Client 可以接收來自 Azure VM (MQTT Broker Server) 的訊息

    參考資源

    C# MQTT using MQTTnet

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置: jsonContent: meta: false pages: false posts: title: true date: true path: true text: false raw: false content: false slug: false updated: false comments: false link: false permalink: false excerpt: false categories: false tags: true
     
    推荐文章
    刚分手的马铃薯  · 
    4 周前
    奔跑的铁板烧  · 
    2 月前