软件效果图
文章插图
软件架构草图
文章插图
效果解释:运行 winform 端后 使用 ctrl+c 先复制任何词语,然后ctrl+空格 就可以将翻译结果显示在 安卓,IOS,windows 甚至 mac 任意客户端1:使用 VS2022 + net6 创建 MAUI 项目,创建不了的先安装
文章插图
2:创建时使用 .NET MAUI 应用,应用名字自己定义 , 我这里用 MauiAppClient
文章插图
3:创建后的项目图
文章插图
4:添加项目引用
CommunityToolkit.MvvmMAUI 的官方 MVVM 库,可以很方便的让C#像VUE那样简单的使用双向绑定MQTTnet 这里我们 MAUI 客户端和服务端之间使用 MQTT 协议来通信Newtonsoft.Json 这个不解释,不引用也可以直接使用官方的 System.Text.Json5:打开 MainPage.xaml 将文件修改为一下内容,MainPage.xaml内容为APP软件主程序窗口页面内容
`<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="MauiAppClient.MainPage"xmlns:viewmodel="clr-namespace:MauiAppClient.ViewModel"x:DataType="viewmodel:MainPageModel"BackgroundColor="Black"><ScrollView><StackLayout Margin="20,35,20,25"><Labelx:Name="LabelTips"Text="{Binding StrTips}"FontSize="12"TextColor="Red"Margin="15"/><Labelx:Name="LabelKey"Text="{Binding StrKey}"FontSize="32"TextColor="GreenYellow"Margin="15"/><Labelx:Name="LabelValue1"Text="{Binding StrValue1}"FontSize="26"TextColor="#08e589"Margin="15"/><Labelx:Name="LabelValue2"Text="{Binding StrValue2}"FontSize="26"TextColor="#08e589"Margin="15"/></StackLayout></ScrollView></ContentPage>`
6:创建页面绑定视图模型 有不熟悉 CommunityToolkit.Mvvm 组件的同学建议先查阅下此组件的使用方式 。加好模型后记得注入一下builder.Services.AddSingleton();public partial class MainPageModel : ObservableObject{[ObservableProperty]public string strTips;[ObservableProperty]public string strKey;[ObservableProperty]public string strValue1;[ObservableProperty]public string strValue2;}
7:MAUI 程序主代码public static IMqttClient _mqttClient;public MainPageModel _vm;public MainPage(MainPageModel vm){InitializeComponent();_vm = vm;BindingContext = _vm;MqttInit();}/// <summary>/// 初始化MQTT/// </summary>public void MqttInit(){string clientId = Guid.NewGuid().ToString();var optionsBuilder = new MqttClientOptionsBuilder().WithTcpServer("xxx.xxx.xxx.xxx", 1883) // 要访问的mqtt服务端的 ip 和 端口号//.WithCredentials("admin", "123456") // 要访问的mqtt服务端的用户名和密码.WithClientId(clientId) // 设置客户端id.WithCleanSession().WithTls(new MqttClientOptionsBuilderTlsParameters{UseTls = false// 是否使用 tls加密});var clientOptions = optionsBuilder.Build();_mqttClient = new MqttFactory().CreateMqttClient();_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync; // 客户端连接成功事件_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync; // 客户端连接关闭事件_mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync; // 收到消息事件_mqttClient.ConnectAsync(clientOptions);}/// <summary>/// 客户端连接关闭事件/// </summary>/// <param name="arg"></param>/// <returns></returns>private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg){_vm.StrTips = "已断开与服务端的连接";int i = 0;Task.Factory.StartNew(() =>{while (_mqttClient == null || _mqttClient.IsConnected == false){i++;Thread.Sleep(5 * 1000);MqttInit();_mqttClient.SubscribeAsync("pc-helper", MqttQualityOfServiceLevel.AtLeastOnce);_vm.StrTips = "尝试重新连..." + i;}}).ConfigureAwait(false);return Task.CompletedTask;}/// <summary>/// 客户端连接成功事件/// </summary>/// <param name="arg"></param>/// <returns></returns>private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg){_vm.StrTips = "已连接服务端";_mqttClient.SubscribeAsync("pc-helper", MqttQualityOfServiceLevel.AtLeastOnce);return Task.CompletedTask;}/// <summary>/// 收到消息事件/// </summary>/// <param name="arg"></param>/// <returns></returns>private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg){string msg = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);var model = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgModel>(msg);_vm.StrKey = "词语:" + model.query?.ToString();string value1 = "翻译:";if (model.translation != null){foreach (var item in model.translation){value1 += item;}}_vm.StrValue1 = value1;string value2 = "解释:";if (model.basic != null && model.basic.explains != null){foreach (var item in model.basic.explains){value2 += item;}}_vm.StrValue2 = value2;return Task.CompletedTask;}public void Publish(string data){var message = new MqttApplicationMessage{Topic = "pc-helper",Payload = Encoding.Default.GetBytes(data),QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,Retain = true// 服务端是否保留消息 。true为保留,如果有新的订阅者连接,就会立马收到该消息 。};_mqttClient.PublishAsync(message);}
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- apijson 初探
- 【日志系统】Loki日志监控 - 入门初体验
- iQOOZ5游戏评测_iQOOZ5游戏体验
- <五>掌握左值引用和初识右值引用
- Hugging Face发布diffuser模型AI绘画库初尝鲜!
- 启初和小浣熊面霜哪个好_启初跟小浣熊哪个更好
- too同义词|too的同义词
- 树的邻接矩阵、双亲孩子表示法…… C++ 不知树系列之初识树
- 小米手环6nfc使用体验_小米手环6nfc使用测评
- 初步玩魔方怎么玩(玩魔方的好处和危害)