MQTT 桌面服务端(基于MQTTnet.Server 5.0.1.1416)

Form.cs

namespace mymqtt
{
    using MQTTnet.Server;
    using System.Buffers;
    using System.Text;

    public partial class Form : System.Windows.Forms.Form
    {
        private MqttServer? _server;
        public Form()
        {
            InitializeComponent();
            this.ButtonStart.Enabled = true;
            this.ButtonStop.Enabled = false;
        }

        private async void ButtonStart_Click(object sender, EventArgs e)
        {
            this.ButtonStart.Enabled = false;
            this.ButtonStop.Enabled = true;
            await this.StartAsync();
        }

        private async void ButtonStop_Click(object sender, EventArgs e)
        {
            this.ButtonStart.Enabled = true;
            this.ButtonStop.Enabled = false;
            await this.StopAsync();
        }

        public async Task StartAsync()
        {
            // 创建服务器
            var options = new MqttServerOptionsBuilder()
                .WithDefaultEndpoint()
                .Build();
            var factory = new MqttServerFactory();
            _server = factory.CreateMqttServer(options);
            // 注册事件
            // [事件]连接验证
            _server.ValidatingConnectionAsync += OnValidatingConnection;
            // [事件]连接成功
            _server.ClientConnectedAsync += OnClientConnected;
            // [事件]断开连接
            _server.ClientDisconnectedAsync += OnClientDisconnected;
            // [事件]发布(接收)消息
            _server.InterceptingPublishAsync += OnInterceptingPublish;
            // [事件]订阅
            _server.InterceptingSubscriptionAsync += OnInterceptingSubscription;
            // [事件]启动
            _server.StartedAsync += OnStarted;
            // [事件]停止
            _server.StoppedAsync += OnStopped;
            // 启动服务器
            await _server.StartAsync();
        }

        public async Task StopAsync()
        {
            if (_server != null)
            {
                await _server.StopAsync();
            }
        }

        public Task OnValidatingConnection(ValidatingConnectionEventArgs e)
        {
            Invoke((EventHandler)delegate
            {
                listBoxMsg.Items.Add("Validating - UserName:" + e.UserName + ",Password:" + e.Password);
            });
            e.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.Success;
            return Task.CompletedTask;
        }

        public Task OnClientConnected(ClientConnectedEventArgs e)
        {
            Invoke((EventHandler)delegate
            {
                this.listBoxMsg.Items.Add("Connected - ClientId:" + e.ClientId);
            });
            return Task.CompletedTask;
        }

        public Task OnClientDisconnected(ClientDisconnectedEventArgs e)
        {
            Invoke((EventHandler)delegate
            {
                this.listBoxMsg.Items.Add("Disconnected - ClientId:" + e.ClientId);
            });
            return Task.CompletedTask;
        }

        public Task OnInterceptingPublish(InterceptingPublishEventArgs e)
        {
            Invoke((EventHandler)delegate
            {
                this.listBoxMsg.Items.Add("Publish - Topic:" + e.ApplicationMessage.Topic
                    + ",Payload:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload.ToArray()));
            });
            return Task.CompletedTask;
        }

        public Task OnInterceptingSubscription(InterceptingSubscriptionEventArgs e)
        {
            Invoke((EventHandler)delegate
            {
                this.listBoxMsg.Items.Add("Subscription - Topic:" + e.TopicFilter.Topic + ",ClientId:" + e.ClientId);
            });
            return Task.CompletedTask;
        }

        public Task OnStarted(EventArgs e)
        {
            this.listBoxMsg.Items.Add("Server Started");
            return Task.CompletedTask;
        }

        public Task OnStopped(EventArgs e)
        {
            this.listBoxMsg.Items.Add("Server Stopped");
            return Task.CompletedTask;
        }

        private void ButtonClear_Click(object sender, EventArgs e)
        {
            this.listBoxMsg.Items.Clear();
        }
    }
}

运行效果

1758956281432

posted on 2025-09-27 14:55  星辰河岳  阅读(25)  评论(0)    收藏  举报