MQTTnet 2.8 及 3.0.16 的使用

来源:https://www.cnblogs.com/chenwolong/archive/2023/03/21/17239760.html
-Advertisement-
Play Games

十年河東,十年河西,莫欺少年窮 學無止境,精益求精 netcore3.1控制台應用程式,引入MQTTnet 2.8版本 訂閱端: using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; ...


十年河東,十年河西,莫欺少年窮

學無止境,精益求精

netcore3.1控制台應用程式,引入MQTTnet 2.8版本

訂閱端:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using MQTTnet;
using MQTTnet.Server; 
using MQTTnet.Client;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using MQTTnet.Protocol;

namespace swapConsole
{
    class Program
    {
        private static MqttClient mqttClient = null;
        private static  string topic = "test123ABC";
        private static IMqttClientOptions Options
        {
            get
            {
                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder(); 
                builder.WithCleanSession(false);
                //用戶名 密碼
                builder.WithCredentials("", "");
                var id = Guid.NewGuid().ToString();
                builder.WithClientId(id);
                builder.WithTcpServer("1270.0.0.0", 1883);
                return builder.Build();
            }
        }
        static async Task Main(string[] args)
        {
            MqttFactory factory = new MqttFactory();
            if (mqttClient == null)
            {
                mqttClient = (MqttClient)factory.CreateMqttClient();
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += async (s, e) =>
                 {
                     Console.WriteLine("嘗試重連!" + Environment.NewLine);
                     await ConnectToServer();
                 };
            }
            await ConnectToServer(); 

            Console.ReadLine();
        }
        /// <summary>
        /// 連接MQTT伺服器
        /// </summary>
        private   static async Task ConnectToServer()
        {
            try
            {
                var res =await  mqttClient.ConnectAsync(Options);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"連接到MQTT伺服器失敗!" + Environment.NewLine + ex.Message + Environment.NewLine);
            }
        }
        /// <summary>
        /// 連接MQTT伺服器觸發
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MqttClient_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("已連接到MQTT伺服器!" + Environment.NewLine);
            SubscribeInfo();
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
        }

        /// <summary>
        /// 訂閱消息
        /// </summary>
        public static void SubscribeInfo()
        {
            if (string.IsNullOrEmpty(topic))
            {
                Console.WriteLine("訂閱主題不能為空!");
                return;
            }

            if (!mqttClient.IsConnected)
            {
                Console.WriteLine("MQTT客戶端尚未連接!");

                return;
            }
            mqttClient.SubscribeAsync(new List<TopicFilter> {
                new  TopicFilter(topic, MqttQualityOfServiceLevel.ExactlyOnce)
            });

            Console.WriteLine($"已訂閱[{topic}]主題" + Environment.NewLine);
        }

        /// <summary>
        /// 退訂消息
        /// </summary>
        public static void UnSubscribeInfo()
        { 

            if (string.IsNullOrEmpty(topic))
            {
                Console.WriteLine("退訂主題不能為空!");
                return;
            }
            if (!mqttClient.IsConnected)
            {
                Console.WriteLine("MQTT客戶端尚未連接!");
                return;
            }
            mqttClient.UnsubscribeAsync(topic);
            Console.WriteLine($"已退訂[{topic}]主題" + Environment.NewLine);
        }

    }
}
View Code

發佈端:

using MQTTnet;
using MQTTnet.Client;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace swapPublish
{
    class Program
    {
        private static MqttClient mqttClient = null;
        private static string topic = "test123ABC";
        private static IMqttClientOptions Options
        {
            get
            {
                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder();
                builder.WithCleanSession(false);
                //用戶名 密碼
                builder.WithCredentials("", "");
                var id = Guid.NewGuid().ToString();
                builder.WithClientId(id);
                builder.WithTcpServer("127.0.0.1", 1883);
                return builder.Build();
            }
        }
        static async Task  Main(string[] args)
        {
            MqttFactory factory = new MqttFactory();
            if (mqttClient == null)
            {
                mqttClient = (MqttClient)factory.CreateMqttClient(); 
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += async(s, e) =>
                {
                    Console.WriteLine("嘗試重連!" + Environment.NewLine);
                    await ConnectToServer();
                };
            }
           await  ConnectToServer();
            Console.WriteLine("已斷開MQTT連接!" + Environment.NewLine);

            Console.ReadLine();
        }
        /// <summary>
        /// 連接MQTT伺服器
        /// </summary>
        private static async Task ConnectToServer()
        {
            try
            {
                var res = await mqttClient.ConnectAsync(Options);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"連接到MQTT伺服器失敗!" + Environment.NewLine + ex.Message + Environment.NewLine);
            }
        }
        /// <summary>
        /// 連接MQTT伺服器觸發
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MqttClient_Connected(object sender, EventArgs e)
        {
            Console.WriteLine("已連接到MQTT伺服器!" + Environment.NewLine);
            for(int i = 0; i < 10; i++)
            {
                var tak = PublishInfo(); 
                Thread.Sleep(2000);
            }
          
        }

        private static async  Task PublishInfo( )
        { 

            if (string.IsNullOrEmpty(topic))
            {
               Console.WriteLine("發佈主題不能為空!");
                return;
            }

            string inputString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            MqttApplicationMessageBuilder builder = new MqttApplicationMessageBuilder(); 
            builder.WithPayload(Encoding.UTF8.GetBytes(inputString));
            builder.WithTopic(topic);
            builder.WithRetainFlag(false);
            builder.WithExactlyOnceQoS();
            await mqttClient.PublishAsync(builder.Build());
        }
    }
}
View Code

 如何只允許一個客戶端消費同一個消息,暫時未解決!

大家有解決方法,請貼出評論。謝謝

MQTTnet  3.0.16 版本的使用

客戶端:

using MQTTnet;
using MQTTnet.Adapter;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace mqttsub
{
    class Program
    {
        static async Task Main(string[] args)
        {
            MqttClient mqtt = new MqttClient();
            await mqtt.StartAsync();
            Console.ReadKey();
        }
    }

    public class MqttClient
    {
        private IMqttClient client; 
        private IMqttClientOptions options;
        MqttClientDto model =null;
        public MqttClient()
        {
            model = new MqttClientDto
            {
                Account = "",
                PassWord = "",
                ClientId = Guid.NewGuid().ToString(),
                IP = "",
                Port = 1883,
                Topic="test/+/ABC" //通配符模式 該模式匹配 test/123/ABC  testABC  test/DDDDD/ABC 等
            };
        }
        public async Task StartAsync()
        {
            try
            {
                client = new MqttFactory().CreateMqttClient();
                var build = new MqttClientOptionsBuilder()
                //配置客戶端Id
                .WithClientId(Guid.NewGuid().ToString())
                //配置登錄賬號
                .WithCredentials(model.Account,model.PassWord)
                //配置伺服器IP埠 這裡得埠號是可空的
                .WithTcpServer(model.IP, 1883)
                .WithCleanSession();

                options = build.Build();
                //收到伺服器發來消息
                client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceivedHandler);
                //client.UseApplicationMessageReceivedHandler(args=> {
                //    Console.WriteLine("===================================================");
                //    Console.WriteLine("收到消息:");
                //    Console.WriteLine($"主題:{args.ApplicationMessage.Topic}");
                //    Console.WriteLine($"消息:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)}");
                //    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++");
                //    Console.WriteLine();
                //});
                //連接成功 
                client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(ConnectedHandler);
                //client.UseConnectedHandler(args=> {
                //    Console.WriteLine("本客戶端已連接成功");
                //    Console.WriteLine($"地址:{model.IP}");
                //    Console.WriteLine($"埠:{model.Port}");
                //    Console.WriteLine($"客戶端:{model.ClientId}");
                //    Console.WriteLine($"賬號:{model.Account}");
                //    Console.WriteLine();
                //    //第1種訂閱方式
                //    client.SubscribeAsync("主題名稱").GetAwaiter().GetResult();

                //    //第2種訂閱方式
                //    List<MqttTopicFilter> Topics = new List<MqttTopicFilter>();
                //    Topics.Add(new MqttTopicFilter() { Topic = "主題名稱A", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce });
                //    Topics.Add(new MqttTopicFilter() { Topic = "主題名稱B" });
                //    Topics.Add(new MqttTopicFilter() { Topic = "主題名稱C" });
                //    client.SubscribeAsync(Topics.ToArray()).GetAwaiter().GetResult();

                //    //第3種訂閱方式
                //    MqttClientSubscribeOptionsBuilder builder = new MqttClientSubscribeOptionsBuilder();
                //    builder.WithTopicFilter("AAA");
                //    client.SubscribeAsync(builder.Build()).GetAwaiter().GetResult();
                //});
                //斷開連接 重連就寫在此處
                client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(DisconnectedHandler);
                //client.UseDisconnectedHandler(args =>
                //{
                //    Console.WriteLine("本客戶端已經斷開連接");
                //    Console.WriteLine();
                //    try
                //    {
                //        client.ConnectAsync(options).GetAwaiter().GetResult();
                //    }
                //    catch (Exception ex)
                //    {
                //        Console.WriteLine("重連失敗");
                //    }
                //});
                //客戶端發送消息
                //await client.PublishAsync("你想要的主題", "你需要發送的東西");
                //await client.PublishAsync("你想要的主題", Encoding.UTF8.GetBytes("你需要發送的東西").ToList());
                //連接
                await client.ConnectAsync(options);
            }
            catch (MqttConnectingFailedException)
            {
                Console.WriteLine("身份校驗失敗");
            }
            catch (Exception ex)
            {
                Console.WriteLine("出現異常");
                Console.WriteLine(ex.Message);
            }
        }


        /// <summary>
        /// 客戶端斷開連接後,如果需要重連在此處實現
        /// </summary>
        /// <param name="obj"></param>
        private async void DisconnectedHandler(MqttClientDisconnectedEventArgs obj)
        {
            Console.WriteLine("本客戶端已經斷開連接");
            Console.WriteLine();
            try
            {
                await client.ConnectAsync(options);
            }
            catch (Exception)
            {
                Console.WriteLine("重連失敗");
            }
        }

        /// <summary>
        /// 連接成功 在此處做訂閱主題(Topic)操作
        /// </summary>
        /// <param name="obj"></param>
        private async void ConnectedHandler(MqttClientConnectedEventArgs obj)
        {
            Console.WriteLine("本客戶端已連接成功");
            Console.WriteLine($"地址:{model.IP}");
            Console.WriteLine($"埠:{model.Port}");
            Console.WriteLine($"客戶端:{model.ClientId}");
            Console.WriteLine($"賬號:{model.Account}");
            Console.WriteLine();
            //第1種訂閱方式
            // client.SubscribeAsync("主題名稱").GetAwaiter().GetResult();

            //第2種訂閱方式
            List<MqttTopicFilter> Topics = new List<MqttTopicFilter>();
            Topics.Add(new MqttTopicFilter() { Topic = model.Topic, QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce});
            //Topics.Add(new MqttTopicFilter() { Topic = "主題名稱B" });
            //Topics.Add(new MqttTopicFilter() { Topic = "主題名稱C" });
            await client.SubscribeAsync(Topics.ToArray());

            //第3種訂閱方式
            //MqttClientSubscribeOptionsBuilder builder = new MqttClientSubscribeOptionsBuilder();
            //builder.WithTopicFilter("AAA");
            //client.SubscribeAsync(builder.Build()).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 收到消息
        /// </summary>
        /// <param name="obj"></param>
        private void MessageReceivedHandler(MqttApplicationMessageReceivedEventArgs obj)
        {
            Console.WriteLine("===================================================");
            Console.WriteLine("收到消息:");
            Console.WriteLine($"主題:{obj.ApplicationMessage.Topic}");
            Console.WriteLine($"消息:{Encoding.UTF8.GetString(obj.ApplicationMessage.Payload)}");
            Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            Console.WriteLine();
        }
    }

    public class MqttClientDto
    {
        /// <summary>
        /// 連接地址
        /// </summary>
        public string IP { get; set; }
        /// <summary>
        /// 賬號
        /// </summary>
        public string Account { get; set; }
        /// <summary>
        /// 密碼
        /// </summary>
        public string PassWord { get; set; }
        /// <summary>
        /// 客戶端Id
        /// </summary>
        public string ClientId { get; set; }

        public int Port { get; set; }

        public string Topic { get; set; }
    }
}
View Code

服務端:

using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MqttPub
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await new ServerDome(). StartAsync();
            Console.Read();
        }
    }

    public class ServerDome  
    {
        private IMqttServer server;
        MqttClientDto model = null;
        public ServerDome()
        {
            model = new MqttClientDto
            {
                Account = "",
                PassWord = "",
                ClientId = Guid.NewGuid().ToString(),
                IP = "",
                Port = 1883,
                Topic = "test"
            };
        }

        public async Task StartAsync()
        {
            if (server == null || !server.IsStarted)
            {

                server = new MqttFactory().CreateMqttServer();
                MqttServerOptionsBuilder serverOptions = new MqttServerOptionsBuilder();
                //、預設監聽埠 
                serverOptions.WithDefaultEndpointPort(model.Port);
                //校驗客戶端信息
                serverOptions.WithConnectionValidator(client => {
                    string Account = client.Username;
                    string PassWord = client.Password;
                    string clientid = client.ClientId;
                    if (Account == "" && PassWord == "")
                    {
                        client.ReasonCode = MqttConnectReasonCode.Success;
                        Console.WriteLine("校驗成功");
                    }
                    else
                    {
                        client.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        Console.WriteLine("校驗失敗");
                    }
                });

                //客戶端發送消息監聽
                server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceivedHandler);
                //server.UseApplicationMessageReceivedHandler(args=>{
                //    Console.WriteLine("===================================================");
                //    Console.WriteLine("收到消息:");
                //    Console.WriteLine($"客戶端:{args.ClientId}");
                //    Console.WriteLine($"主題:{args.ApplicationMessage.Topic}");
                //    Console.WriteLine($"消息:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)}");
                //    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++");
                //    Console.WriteLine();
                //});
                //客戶端連接事件
                server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(ClientConnectedHandler);
                //server.UseClientConnectedHandler(args =>
                //{
                //    Console.WriteLine($"{args.ClientId}此客戶端已經連接到伺服器");
                //});
                //客戶端斷開連接事件
                server.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(ClientDisconnectedHandler);
                //server.UseClientDisconnectedHandler(args => {
                //    Console.WriteLine($"斷開連接的客戶端:{args.ClientId}");
                //    Console.WriteLine($"斷開連接類型:{args.DisconnectType.ToString()}");
                //});

                //客戶端訂閱主題事件
                server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(ClientSubscribedTopicHandler);
                //客戶端取消訂閱主題事件
                server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(ClientUnsubscribedTopicHandler);
                //伺服器啟動事件
                server.StartedHandler = new MqttServerStartedHandlerDelegate(StartedHandler);
                //伺服器停止事件
                server.StoppedHandler = new MqttServerStoppedHandlerDelegate(StoppedHandler);
                //服務端發送數據
                //await  server.PublishAsync("你想要的主題","你需要發送的東西");
                //var mqttApplicationMessage = new MqttApplicationMessage();
                //mqttApplicationMessage.Topic = "你想要的主題";
                //mqttApplicationMessage.Payload = Encoding.ASCII.GetBytes("你需要發送的東西");
                //await server.PublishAsync(mqttApplicationMessage);
                //啟動伺服器
                await server.StartAsync(serverOptions.Build());
            }
        }

        public async Task StopAsync()
        {
            if (server != null)
            {
                if (server.IsStarted)
                {
                    	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 資源調度器是 YARN 中最核心的組件之一,它是 ResourceManager 中的一個插拔式服務組件,負責整個集群資源的管理和分配。 Yarn 預設提供了三種可用資源調度器,分別是FIFO (First In First Out )、 Yahoo! 的 Capacity Scheduler 和 ... ...
  • 安全配置Security Defenses 通過對Security Defenses的配置 ,可以對http頭添加相應的安全配置 ,如csp, X-Frame-Options, X-Content-Type-Option等 1 X-Frame-Options 你的網站添加了X-Frame-Optio ...
  • 說明 使用 VLD 記憶體泄漏檢測工具輔助開發時整理的學習筆記。 1. 使用前的準備 參考本人另一篇博客 安裝 Visual Leak Detector 下載 vld-2.5.1-setup.exe 並按步驟安裝 VLD。這一種使用方式的缺點是,當把項目拷貝到別的電腦上編譯運行時,需要按以下流程重新配 ...
  • 由於 Blazor-WebAssembly 是在瀏覽器中運行的,通常不需要執行伺服器代碼,只要有個“窩”能托管並提供相關文件的下載即可。所以,當你有一個現成的 Blazor wasm 項目,沒必要用其他語言重寫,或者你不想用 ASP.NET Core 來托管(有些大材小用了),就可以試試用 node ...
  • 1. Grid佈局 ,(Table 佈局) 兩行兩列佈局, Border 0 行 0 列預設開始 <Window x:Class="WpfApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
  • 1 枚舉 enum E_MonsterType//定義了一個枚舉的變數類型 { normal1,//0 boss = 5,//5 normal2,//6,前一個自動加1 } //枚舉和switch語句天生一對,寫switch時能對枚舉類型自動補全 E_MonsterType monsterType ...
  • 用了很多年的Rapid SCADA v5,現在官網已經推出了v6,就簡單寫一下有關v6的安裝指南吧。 本指南面向Windows用戶,不適用於linux用戶 步驟 從官網下載Rapid SCADA最新的RC版本的v6,然後運行壓縮包內的ScadaSetup.exe程式。 FAQ 提示埠占用 Rapi ...
  • 簡介 本文主要介紹使用 利用 SqlSugar 來實現多資料庫的維護 ,動態建類CRUD,動態建表 ,全局過濾器 ,跨庫查詢等功能 1、創建表 SqlSugar支持了3種模式的建表(無實體建表、實體建表,實體特性建表),非常的靈活 可以多個資料庫 MYSQL MSSQL ORACLE SQLITE ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...