C#MQTT编程07--MQTT服务器和客户端(wpf版)

news2024/11/17 7:37:25

1、前言

上篇完成了winform版的mqtt服务器和客户端,实现了订阅和发布,效果666,长这样

 这节要做的wpf版,长这样,效果也是帅BBBB帅,wpf技术是cs程序软件的福音。

 wpf的基础知识和案例项目可以看我的另一个专栏系列文章,这里直接干搞,开发环境依然是vs2022,.netframework 4.8,mqttnet3.x。

WPF真入门教程

2、服务器搭建

1、创建项目方案

 2、添加包组件MQTTNET 

3、创建相关的目录及文件 

 

样式文件CommonStyle.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="ButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="#3F85FF"></Setter>
        <Setter Property="Foreground" Value="White"></Setter>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"></Setter>
        <Setter Property="Margin" Value="5"></Setter>
        <Setter Property="FontSize" Value="16"></Setter>
        <!--模板的样式-->
        <Setter Property="Template">
            <Setter.Value>
                <!--Button单选按钮样式-->
                <ControlTemplate TargetType="Button">
                    <Grid >
                        <Border Background="{TemplateBinding Background}" CornerRadius="5" >
                            <TextBlock Margin="10 5 10 5" Text="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <!--鼠标放上去时的触发器-->
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="DarkOliveGreen" ></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers> 
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

4、设置UI布局界面 

 

<Window x:Class="MQTTNETServerWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MQTTNETServerWPF.ViewModel"
        mc:Ignorable="d" Background="Transparent" WindowStartupLocation="CenterScreen"
        FontSize="13" FontFamily="Microsoft YaHei" FontWeight="ExtraLight" Foreground="#333"
        Title="MainWindow" Height="550" Width="890">
    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="-1"/>
    </WindowChrome.WindowChrome>
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <Grid ShowGridLines="true"  >
        <Grid.RowDefinitions>
            <RowDefinition Height="70"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" FontWeight="Bold" Background="BlanchedAlmond"  Text="WPF版MQTT服务器程序" FontSize="25" VerticalAlignment="Center" Margin="6,20,0,0" Foreground="#666"   />
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="220"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border BorderBrush="#EEE" BorderThickness="0,0,1,0"/>

            <!--左侧布局-->
            <StackPanel Grid.Column="0" Margin="20" >
                <TextBlock Text="主机地址"/>
                <TextBox Text="{Binding Server.ServerIP}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"  />
                <TextBlock Text="端口号" Margin="0,10,0,0"/>
                <TextBox Text="{Binding Server.ServerPort}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"  />
                <TextBlock Text="连接账号" Margin="0,10,0,0"/>
                <TextBox Text="{Binding Server.ServerName}"  Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"    />
                <TextBlock Text="连接密码" Margin="0,10,0,0"/>
                <TextBox Text="{Binding Server.ServerPwd}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"  />
                <Button Content="启动服务" Margin="0,30,0,0" Height="30"  Command="{Binding StartCommand}" Style="{StaticResource ButtonStyle}" />
                <Button Content="停止服务" Margin="0,10" Height="30"  Command="{Binding StopCommand}"  Style="{StaticResource ButtonStyle}"/>
            </StackPanel>

            <!--右侧布局-->
            <Grid Grid.Column="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="2*"/>
                    <RowDefinition Height="3*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <GridSplitter VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Height="4" Background="#F7F9FA" Grid.ColumnSpan="2" Margin="0,0,3,0"/>

                <Grid Margin="20,20,10,15">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="在线Client列表"/>
                    <ListBox Grid.Row="1"   ItemsSource="{Binding ClientsList}"/>
                </Grid>

                <Grid Margin="10,20,20,15" Grid.Column="1">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="Topic主题列表"/>
                    <ListView Grid.Row="1"   ItemsSource="{Binding TopicsList}">
                    </ListView>
                </Grid>

                <Grid Grid.Row="1" Grid.ColumnSpan="2" Margin="20,10,20,20">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="消息"/>
                    <TextBox  Grid.Row="1"   x:Name="txtRich" ToolTip="右键清理内容" Text="{Binding ConnectWords}" Height="200" Background="White" VerticalContentAlignment="Top" Padding="3,0" Margin="10,9,10,10"    >
                        <!--添加一个右键菜单的功能,即清空-->
                        <TextBox.ContextMenu>
                            <ContextMenu>
                                <MenuItem x:Name="menuClear" Click="miClear_Click"  Header="清空内容"></MenuItem>
                            </ContextMenu>
                        </TextBox.ContextMenu>
                    </TextBox>
                </Grid>
            </Grid>
        </Grid>
    </Grid>
</Window>

5、视图模型,属性绑定和命令绑定

完整代码:

using MQTTnet.Client.Receiving;
using MQTTnet;
using MQTTnet.Server;
using MQTTNETServerWPF.Command;
using MQTTNETServerWPF.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Collections.ObjectModel;
using MQTTnet.Certificates;
using MQTTnet.Protocol;
using System.Runtime.Remoting.Messaging;

namespace MQTTNETServerWPF.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
       
        private IMqttServer mqttserver;//mqtt服务器
        List<TopicItem> Topics = new List<TopicItem>();

        public MainWindowViewModel()
        {
            //创建服务器对象
            mqttserver = new MqttFactory().CreateMqttServer();
            mqttserver.ApplicationMessageReceivedHandler =
                new MqttApplicationMessageReceivedHandlerDelegate(new Action<MqttApplicationMessageReceivedEventArgs>(Server_ApplicationMessageReceived));//绑定消息接收事件
            mqttserver.ClientConnectedHandler =
                new MqttServerClientConnectedHandlerDelegate(new Action<MqttServerClientConnectedEventArgs>(Server_ClientConnected));//绑定客户端连接事件
            mqttserver.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(new Action<MqttServerClientDisconnectedEventArgs>(Server_ClientDisconnected));//绑定客户端断开事件
            mqttserver.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(new Action<MqttServerClientSubscribedTopicEventArgs>(Server_ClientSubscribedTopic));//绑定客户端订阅主题事件
            mqttserver.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(new Action<MqttServerClientUnsubscribedTopicEventArgs>(Server_ClientUnsubscribedTopic));//绑定客户端退订主题事件
            mqttserver.StartedHandler = new MqttServerStartedHandlerDelegate(new Action<EventArgs>(Server_Started));//绑定服务端启动事件
            mqttserver.StoppedHandler = new MqttServerStoppedHandlerDelegate(new Action<EventArgs>(Server_Stopped));//绑定服务端停止事件
        }

        #region 方法

        /// 绑定消息接收事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            string msg = e.ApplicationMessage.ConvertPayloadToString();
            WriteLog(">>> 收到消息:" + msg + ",QoS =" + e.ApplicationMessage.QualityOfServiceLevel + ",客户端=" + e.ClientId + ",主题:" + e.ApplicationMessage.Topic);
        }

        /// <summary>
        /// 绑定客户端连接事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_ClientConnected(MqttServerClientConnectedEventArgs e)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    this.ClientsList.Add(e.ClientId);
                });
                WriteLog(">>> 客户端" + e.ClientId + "连接");
            });
        }

        /// <summary>
        /// 绑定客户端断开事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_ClientDisconnected(MqttServerClientDisconnectedEventArgs e)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    this.ClientsList.Remove(e.ClientId);
                });
                WriteLog(">>> 客户端" + e.ClientId + "断开");
            });
        }

        /// <summary>
        /// 绑定客户端订阅主题事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_ClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs e)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    var topic = Topics.FirstOrDefault(t => t.Topic == e.TopicFilter.Topic);
                    if (topic == null)
                    {
                        topic = new TopicItem { Topic = e.TopicFilter.Topic, Count = 0 };
                        Topics.Add(topic);
                    }
                    if (!topic.Clients.Exists(c => c == e.ClientId))
                    {
                        topic.Clients.Add(e.ClientId);
                        topic.Count++;
                    }

                    this.TopicsList.Clear();
                    foreach (var item in this.Topics)
                    {
                        this.TopicsList.Add($"{item.Topic}:{item.Count}");
                    }
                });
                WriteLog(">>> 客户端" + e.ClientId + "订阅主题" + e.TopicFilter.Topic);
            });
        }

        /// <summary>
        /// 绑定客户端退订主题事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_ClientUnsubscribedTopic(MqttServerClientUnsubscribedTopicEventArgs e)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    var topic = Topics.FirstOrDefault(t => t.Topic == e.TopicFilter);
                    if (topic != null)
                    {
                        topic.Count--;
                        topic.Clients.Remove(e.ClientId);
                    }

                    this.TopicsList.Clear();
                    foreach (var item in this.Topics)
                    {
                        this.TopicsList.Add($"{item.Topic}:{item.Count}");
                    }
                });
                WriteLog(">>> 客户端" + e.ClientId + "退订主题" + e.TopicFilter);
            });
        }

        /// <summary>
        /// 绑定服务端启动事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_Started(EventArgs e)
        {
            WriteLog(">>> 服务端已启动!");
        }

        /// <summary>
        /// 绑定服务端停止事件
        /// </summary>
        /// <param name="e"></param>
        private void Server_Stopped(EventArgs e)
        {
            WriteLog(">>> 服务端已停止!");
        }

        /// <summary>
        /// 显示日志
        /// </summary>
        /// <param name="message"></param>
        public void WriteLog(string message)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    ConnectWords = message + "\r";
                });
            });
        }

        #endregion



        #region 属性
        private MqttServerModel server = new MqttServerModel("127.0.0.1", "1869", "boss", "1234");//服务器实体
        /// <summary>
        /// 当前服务器对象
        /// </summary>
        public MqttServerModel Server
        {
            get { return server; }
            set
            {
                server = value;
                OnPropertyChanged();
            }
        }

        private string connectWords = "";
        /// <summary>
        /// 连接状态
        /// </summary>
        public string ConnectWords
        {
            get { return connectWords; }
            set
            {
                connectWords = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<string> clientsList = new ObservableCollection<string>();
        /// <summary>
        /// 客户列表
        /// </summary>
        public ObservableCollection<string> ClientsList
        {
            get { return clientsList; }
            set
            {
                clientsList = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<string> topicsList = new ObservableCollection<string>();
        /// <summary>
        /// 主题列表
        /// </summary>
        public ObservableCollection<string> TopicsList
        {
            get { return topicsList; }
            set
            {
                topicsList = value;
                OnPropertyChanged();
            }
        }
        #endregion




        #region 命令
        /// <summary>
        /// 启动命令
        /// </summary>
        [Obsolete]
        public ICommand StartCommand
        {
            get
            {
                return new RelayCommand(async o =>
                {
                    var optionBuilder = new MqttServerOptionsBuilder()
                .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(Server.ServerIP))
                .WithDefaultEndpointPort(int.Parse(Server.ServerPort))
                .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(5000))
                .WithConnectionValidator(t =>
                {
                    string un = "", pwd = "";
                    un = Server.ServerName;
                    pwd = Server.ServerPwd;
                    if (t.Username != un || t.Password != pwd)
                    {
                        t.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    }
                    else
                    {
                        t.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                    }
                });
                    var option = optionBuilder.Build();
                    //启动
                    await mqttserver.StartAsync(option);
                }
                );
            }
        }

        /// <summary>
        /// 启动命令
        /// </summary>
        [Obsolete]
        public ICommand StopCommand
        {
            get
            {
                return new RelayCommand(async o =>
                { 
                    if (server != null)
                    {
                        await mqttserver.StopAsync();
                    } 
                });
            }
        }
        #endregion

    }
}

 注意一个地方,就是给文本框添加了一个右键“清空”的功能,看看是怎么样实现的?

 6、启动测试服务器

启动成功,服务器kokokokoko!!!!

 3、客户端创建

1、添加项目MQTTNETClientWPF

2、添加客户端的组件

 

3、创建相关的类文件及目录 

 

4、设计UI布局

 布局仔细 看下

<Window x:Class="MQTTNETClientWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MQTTNETClientWPF.ViewModel"
              mc:Ignorable="d" Background="Transparent" WindowStartupLocation="CenterScreen"
        FontSize="13" FontFamily="Microsoft YaHei" FontWeight="ExtraLight" Foreground="#333"
        Title="MainWindow" Height="600" Width="850">
    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="-1"/>
    </WindowChrome.WindowChrome>
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <Grid  ShowGridLines="true" >
        <Grid.RowDefinitions>
            <RowDefinition Height="70"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" FontWeight="Bold"  Text="WPF版MQTT客户端程序" FontSize="25" VerticalAlignment="Center" Margin="6,20,0,0" Foreground="#666" Background="BlanchedAlmond"  />

        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="220"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border BorderBrush="#EEE" BorderThickness="0,0,1,0"/>

            <StackPanel Margin="20">
                <TextBlock Text="主机地址"/>
                <TextBox Text="{Binding Client.ServerIP}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10" Name="tbHostAddr"/>
                <TextBlock Text="端口号" Margin="0,5,0,0"/>
                <TextBox  Text="{Binding Client.ServerPort}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"   Name="tbHostPort"/>
                <TextBlock Text="连接账号" Margin="0,5,0,0"/>
                <TextBox  Text="{Binding Client.ServerName}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10" Name="tbUsername"/>
                <TextBlock Text="连接密码" Margin="0,5,0,0"/>
                <TextBox Text="{Binding Client.ServerPwd}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"  Name="tbPassword"/>
                <TextBlock Text="客户端ID" Margin="0,5,0,0"/>
                <TextBox Text="{Binding Client.ClientId}" Height="30" VerticalContentAlignment="Center" Padding="5,0" Margin="0,10"   Name="tbClientId"/>
                <Button Content="连接" Margin="0,30,0,0" Height="30" Command="{Binding OpenCommand}"  Style="{StaticResource ButtonStyle}"/>
                <Button Content="断开" Margin="0,10" Height="30"  Command="{Binding CloseCommand}" Style="{StaticResource ButtonStyle}"/>
            </StackPanel>

            <Grid Grid.Column="1" Margin="20,10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>

                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition Height="50"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="auto"/>
                    </Grid.ColumnDefinitions>
                    <Border Background="#F7F9FA" Grid.ColumnSpan="3"/>
                    <TextBlock Text="订阅" VerticalAlignment="Center" Margin="5,0"/>
                    <TextBlock Text="主题" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5,0"/>
                    <TextBox Text="{Binding Topic}" Grid.Row="1" Height="30" Padding="5,0" VerticalContentAlignment="Center" Grid.Column="1"  Name="tbTopic"/>
                    <Button Width="50" Grid.Row="1" Height="30" Content="订阅" Grid.Column="2" Margin="5,10,0,10"   Command="{Binding SubscriteCommand}"  Style="{StaticResource ButtonStyle}"  HorizontalAlignment="Left"/>
                </Grid>

                <Grid Grid.Row="1" Margin="0,20">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition Height="50"/>
                        <RowDefinition Height="30"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="auto"/>
                    </Grid.ColumnDefinitions>
                    <Border Background="#F7F9FA" Grid.ColumnSpan="3"/>
                    <TextBlock Text="发布" VerticalAlignment="Center" Margin="5,0"/>
                    <TextBlock Text="主题" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5,0"/>
                    <TextBox Text="{Binding Topic}" Grid.Row="1" Height="30" Padding="5,0" VerticalContentAlignment="Center" Grid.Column="1"   Name="tbPubTopic"/>
                    <TextBlock Text="内容" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5,0"/>
                    <TextBox Text="{Binding Pubmsg}"  Grid.Row="2" Height="30" Padding="5,0" VerticalContentAlignment="Center" Grid.Column="1"  Name="tbContent"/>
                    <Button Width="50" Grid.Row="2" Height="30"  Content="发布" Grid.Column="2" Margin="5,0,5,0"  Command="{Binding PublishCommand}"  Style="{StaticResource ButtonStyle}"  VerticalAlignment="Top"/>
                </Grid>

                <Grid Grid.Row="2" Margin="0,10,0,0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="30"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Border Background="#F7F9FA" Grid.ColumnSpan="3"/>
                    <TextBlock Text="消息" VerticalAlignment="Center" Margin="5,0"/>
                    <TextBox  Grid.Row="1"  x:Name="txtRich" ToolTip="右键清理内容" Text="{Binding ConnectWords}" Height="200"  Background="White" VerticalContentAlignment="Top"  Padding="3,0" Margin="10,9,75,10"  >
                        <!--添加一个右键菜单的功能,即清空-->
                        <TextBox.ContextMenu>
                            <ContextMenu>
                                <MenuItem x:Name="menuClear" Click="miClear_Click"  Header="清空内容"></MenuItem>
                            </ContextMenu>
                        </TextBox.ContextMenu>
                    </TextBox>
                </Grid>
            </Grid>
        </Grid>
    </Grid>
</Window>

5、视图模型viewmodel

模型类的属性绑定和命令绑定,数据驱动控件,即Mvvm渲染方法

using MQTTnet.Client.Options;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTNETClientWPF.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MQTTNETClientWPF.Model;
using MQTTnet;

namespace MQTTNETClientWPF.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        private IManagedMqttClient mqttClient; //mqtt客户端


        public MainWindowViewModel()
        {
            var factory = new MqttFactory();
            mqttClient = factory.CreateManagedMqttClient();//创建客户端对象

            //绑定断开事件
            mqttClient.UseDisconnectedHandler(async ee =>
            {
                WriteLog(DateTime.Now.ToString() + "与服务器之间的连接断开了,正在尝试重新连接");
                // 等待 5s 时间
                await Task.Delay(TimeSpan.FromSeconds(5));
                try
                {
                    mqttClient.UseConnectedHandler(cc =>
                    {
                        WriteLog(">>> 连接到服务成功!");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"重新连接服务器失败:{ex}");
                }
            });

            //绑定接收事件
            mqttClient.UseApplicationMessageReceivedHandler(aa =>
            {
                 try
                {
                    string msg = aa.ApplicationMessage.ConvertPayloadToString();
                    WriteLog(">>> 消息:" + msg + ",QoS =" + aa.ApplicationMessage.QualityOfServiceLevel + ",客户端=" + aa.ClientId + ",主题:" + aa.ApplicationMessage.Topic);
                }
                catch (Exception ex)
                {
                    WriteLog($"+ 消息 = " + ex.Message);
                } 
            });

            //绑定连接事件
            mqttClient.UseConnectedHandler(ee =>
            {
                WriteLog(">>> 连接到服务");
            });
        }

        /// <summary>
        /// 显示日志
        /// </summary>
        /// <param name="message"></param> 
        public void WriteLog(string message)
        {
            Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    ConnectWords = message + "\r";
                });
            });
        }

        #region 属性

        private MqttClientModel client = new MqttClientModel("127.0.0.1", "1869", "boss", "1234", "c1");//服务器实体

        /// <summary>
        /// 连接对象
        /// </summary>
        public MqttClientModel Client
        {
            get { return client; }
            set
            {
                client = value;
                OnPropertyChanged();
            }
        }

        private string connectWords = "";
        /// <summary>
        /// 连接状态
        /// </summary>
        public string ConnectWords
        {
            get { return connectWords; }
            set
            {
                connectWords = value;
                OnPropertyChanged();
            }
        }

        private string topic = "shanghai";
        /// <summary>
        /// 主题
        /// </summary>
        public string Topic
        {
            get { return topic; }
            set
            {
                topic = value;
                OnPropertyChanged();
            }
        }

        private string pubmsg = "0103";
        /// <summary>
        /// 发布
        /// </summary>
        public string Pubmsg
        {
            get { return pubmsg; }
            set
            {
                pubmsg = value;
                OnPropertyChanged();
            }
        }
        #endregion


        #region 命令
        /// <summary>
        /// 连接命令
        /// </summary> 
        public ICommand OpenCommand
        {
            get
            {
                return new RelayCommand(async o =>
                {
                    var mqttClientOptions = new MqttClientOptionsBuilder()
                             .WithClientId(this.Client.ClientId)
                             .WithTcpServer(this.Client.ServerIP, int.Parse(this.Client.ServerPort))
                             .WithCredentials(this.Client.ServerName, this.Client.ServerPwd);

                    var options = new ManagedMqttClientOptionsBuilder()
                                .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                .WithClientOptions(mqttClientOptions.Build())
                                .Build();
                    //开启
                    var t = mqttClientOptions;
                    await mqttClient.StartAsync(options);
                });
            }
        }

        /// <summary>
        /// 断开命令
        /// </summary> 
        public ICommand CloseCommand
        {
            get
            {
                return new RelayCommand(async o =>
                {
                    if (mqttClient != null)
                    {
                        if (mqttClient.IsStarted)
                        {
                            await mqttClient.StopAsync();
                        }
                        mqttClient.Dispose();
                    }
                });
            }
        }

        /// <summary>
        /// 订阅命令
        /// </summary> 
        [Obsolete]
        public ICommand SubscriteCommand
        {
            get
            {
                return new RelayCommand(async o =>
                {
                    if (string.IsNullOrWhiteSpace(this.Topic))
                    {
                        WriteLog(">>> 请输入主题");
                        return;
                    }

                    //在 MQTT 中有三种 QoS 级别: 
                    //At most once(0) 最多一次
                    //At least once(1) 至少一次
                    //Exactly once(2) 恰好一次
                    //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(this.tbTopic.Text).WithAtMostOnceQoS().Build());//最多一次, QoS 级别0
                    await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(this.Topic).WithAtLeastOnceQoS().Build());//恰好一次, QoS 级别1 

                    WriteLog($">>> 成功订阅 {this.Topic}");
                });
            }
        }

        /// <summary>
        /// 发布命令
        /// </summary> 
        public ICommand PublishCommand
        {
            get
            {
                return new RelayCommand(async o =>
                {
                    if (string.IsNullOrWhiteSpace(this.Topic))
                    {
                        WriteLog(">>> 请输入主题");
                        return;
                    }
                    var result = await mqttClient.PublishAsync(
                        this.Topic,
                        this.Pubmsg,
                        MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);//恰好一次, QoS 级别1 
                    WriteLog($">>> 主题:{this.Topic},消息:{this.Pubmsg},结果: {result.ReasonCode}");
                });
            }
        }

        #endregion

    }
}

6、启动客户端

比较屌

4、测试mqtt

 

1、启动服务器,客户端连接成功

 2、测试订阅

3、测试发布

 再启动一个客户端程序,有人不知道如何启动,看下面

c1发布一个消息,看看c1,c2有没有收到,很明显都收到了

 服务器显示有关信息,完全good

基于mqttnet实现的wpf版通信,完美实现,效果飞起来了,颜值高,效果好,帅B得上了飞机。

5、完整代码打包下载 

链接:https://pan.baidu.com/s/1sfQnGEEcsRTBKUSDOdCeTA 
提取码:z2hj 

讲解不易,分析不易,原创不易,整理不易,伙伴们动动你的金手指,你的支持是我最大的动力。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1396857.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

定义域【高数笔记】

【定义域】 1&#xff0c;{知识点} 对于一个函数&#xff0c;f(x)&#xff0c;"f"是起到两个作用&#xff0c;第一&#xff0c;是对自变量的范围的约束&#xff0c;第二&#xff0c;是对运算的约束&#xff0c;同一个"f" 就有同一个约束效果 2&#xff0c;…

TPU编程竞赛系列|第八届集创赛“算能杯“报名开启!

近日&#xff0c;第八届全国大学生集成电路创新创业大赛正式开幕&#xff0c;"算能杯"以 基于TPU处理器的边缘计算系统设计 为赛题&#xff0c;围绕算能提供的多款TPU硬件&#xff0c;展开软硬件协同设计&#xff0c;创新开发算法及探索新兴应用。我们诚邀全国高校的…

表的增删改查 进阶(二)

&#x1f3a5; 个人主页&#xff1a;Dikz12&#x1f525;个人专栏&#xff1a;MySql&#x1f4d5;格言&#xff1a;那些在暗处执拗生长的花&#xff0c;终有一日会馥郁传香欢迎大家&#x1f44d;点赞✍评论⭐收藏 目录 3.新增 4.查询 聚合查询 聚合函数 GROUP BY子句 HA…

php反序列化之pop链构造(基于重庆橙子科技靶场)

常见魔术方法的触发 __construct() //创建类对象时调用 __destruct() //对象被销毁时触发 __call() //在对象中调用不可访问的方法时触发 __callStatic() //在静态方式中调用不可访问的方法时触发 __get() //调用类中不存在变量时触发&#xff08;找有连续箭头的…

Git学习笔记(第3章):Git常用命令

目录 3.1 设置用户签名 3.2 初始化本地库 3.3 查看本地库状态 3.4 添加暂存区 3.5 提交本地库 3.6 历史版本 3.7 修改文件 3.8 版本穿梭 小结 命令 作用 git config --global user.name 用户名 设置用户签名 git config --global user.email 邮箱 设置用户签名 …

机器学习顶会ICLR 2024录用论文合集,包含时间序列、图大模型、agent等热门主题

朋友们&#xff0c;ICLR 2024这周放榜了&#xff01;据统计&#xff0c;本届会议共收到了7262篇论文&#xff0c;整体接收率约为31%&#xff0c;与去年&#xff08;31.8%&#xff09;基本持平。其中Spotlight论文比例为5%&#xff0c;Oral论文比例为1.2%。 不知道各位看完有什…

排序链表(LeetCode 148)

文章目录 1.问题描述2.难度等级3.热门指数4.解题思路参考文献 1.问题描述 给你链表的头结点 head &#xff0c;请将其按 升序 排列并返回 排序后的链表 。 示例 1&#xff1a; 输入&#xff1a;head [4,2,1,3] 输出&#xff1a;[1,2,3,4]示例 2&#xff1a; 输入&#xff…

经典计算机网络面试题

1.说说HTTP常用的状态码及其含义&#xff1f; 状态码 类别 1xx 信息性状态码 2xx 成功状态码 3xx 重定向状态码 4xx 客户端错误状态码 5xx 服务端错误状态码 日常开发中的状态码&#xff1a; 状态码 含义 101 切换请求协议 200 请求成功 301 永久性重定向&…

网络:FTP

1. FTP 文件传输协议&#xff0c;FTP是用来传输文件的协议。使用FTP实现远程文件传输的同时&#xff0c;还可以保证数据传输的可靠性和高效性。 2. 特点 明文传输。 作用&#xff1a;可以从服务器上下载文件&#xff0c;或将本地文件上传到服务器。 3. FTP原理 FTP有控制层面…

原神官网切换效果

这两天来研究一下原神游戏官网的效果&#xff0c;地址&#xff1a;《原神》官方网站-全新4.3版本「蔷薇与铳枪」上线&#xff01; (mihoyo.com) 继续用我之前的模板项目&#xff1a; 等我把这一页写满&#xff0c;会上传原码。 效果很多&#xff0c;我们先看第一个&#xff…

数学建模美赛资料(赛题+获奖论文更新)

数学建模美赛历年真题可以帮助我们了解比赛的出题思路&#xff0c;对建模比赛有一个大致的了解。 在备赛过程中&#xff0c;通过往年真题&#xff0c;我们可以了解考试的范围和重点&#xff0c;做到心中有数&#xff0c;可以有的放矢。通过真题&#xff0c;我们可以感受到各个…

逻辑运算符

逻辑运算符 什么是逻辑运算符&#xff1f; 在数学中&#xff0c;一个数据x大于5&#xff0c;小于15&#xff0c;我们可以这样来进行表示&#xff1a;5<x<15.在Java中&#xff0c;需要把上面的式子先进行拆解&#xff0c;再进行合并表达。 拆解为&#xff1a;x>5和 x…

Python中HTTP代理的配置和使用

在Python中&#xff0c;HTTP代理是一种常用的技术&#xff0c;用于控制和修改HTTP请求和响应。通过使用HTTP代理&#xff0c;我们可以更好地控制网络请求的行为&#xff0c;提高安全性、隐私性和效率。下面我们将详细介绍如何在Python中配置和使用HTTP代理。 一、配置HTTP代理…

泛型编程——模板详解

文章目录 1. 前言2. 泛型编程3. 函数模板3.1 函数模板的概念3.2 函数模板的格式3.3 函数模板的原理3.4 函数模板的实例化3.5 模板参数的匹配原则 4. 类模板4.1 类模板的定义格式4.2 类模板的实例化 5. 模板参数6. 模板的特化6.1 概念6.2 函数模板特化6.3 类模板特化6.3.1 全特化…

【STM32】STM32学习笔记-I2C通信外设(34)

00. 目录 文章目录 00. 目录01. I2C简介02. I2C外设简介03. I2C框图04. I2C基本结构05. 主机发送06. 主机接收07. 软件/硬件波形对比08. 预留09. 附录 01. I2C简介 I2C(Inter&#xff0d;Integrated Circuit)总线是一种由NXP&#xff08;原PHILIPS&#xff09;公司开发的两线式…

链表练习 Leetcode234.回文链表

题目传送门&#xff1a;Leetcode234 给你一个单链表的头节点 head &#xff0c;请你判断该链表是否为回文链表。如果是&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 示例 1&#xff1a; 输入&#xff1a;head [1,2,2,1] 输出&#xff1a;true示例 2&…

element中表格组件的row-class-name和class-name属性的使用以及无效处理

1.这两个属性的使用&#xff0c;row-class-name用在el-table标签上&#xff0c;class-name用在el-table-column标签上。两个属性即可绑定类名也可绑定函数 <!-- 这里是绑定函数&#xff0c;也可以绑定类名 --> <el-table :data"tableData" selection-chang…

Ubuntu安装zsh

安装zsh sudo apt install zsh安装git&#xff08;如果有跳过&#xff09; sudo apt install git(1条消息) 关于Git这一篇就够了_17岁boy想当攻城狮的博客-CSDN博客 安装oh my zsh git clone https://github.com/robbyrussell/oh-my-zsh切换目录到oh-my-zsh文件夹下的tools…

VUE--插槽slot(将父级的模块片段插入到子级中)

组件可以接收任意类型的JS值作为props&#xff0c;但我们想要为子组件传递一些模板片段&#xff0c;并在子组件中进行渲染时&#xff0c;此时可以采用插槽slot来实现 简单来说&#xff0c;插槽时组件内留一个或多个插槽的位置&#xff0c;供组件传递对应的模板代码&#xff08;…

ASCII码常用

ASCII码的意义 对程序员来说真的是意义重大啊&#xff01; 作为一名程序员一定要牢记&#xff01; 常用A&#xff1a;65 a&#xff1a;97