基本信息
源码名称:使用MqttNet自建mqtt服务端(broker)并实现客户端发布订阅消息 入门级示例源码
源码大小:5.91M
文件格式:.zip
开发语言:C#
更新时间:2018-10-01
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

本示例主要实现了以下三点:

1. 自建了mqtt 服务端(broker),并可以接收客户端发来的各种topic

2. 实现了客户端发布订阅mqtt消息

3. 实现了 服务端直接向外广播topic,客户端只需要 订阅该topic即可


调试步骤如下:

1. 运行>>cmd>>  cd 至 MQTTnet.TestApp.AspNetCore2 目录,并执行 dotnet run

2. 浏览器输入 http://localhost:5000 即可看到如下截图,浏览器输入 http://localhost:5000/publish 即可通过服务端发布topic

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using MQTTnet;
using MQTTnet.AspNetCore;
using MQTTnet.Server;
using Newtonsoft.Json;

namespace MQTTnet.TestApp.AspNetCore2
{
    public class Startup
    {
        // In class _Startup_ of the ASP.NET Core 2.0 project.

        public void ConfigureServices(IServiceCollection services)
        {
            var mqttServerOptions = new MqttServerOptionsBuilder()
                .WithoutDefaultEndpoint()
                .Build();
            services
                .AddHostedMqttServer(mqttServerOptions)
                .AddMqttConnectionHandler()
                .AddConnections();
        }

        // In class _Startup_ of the ASP.NET Core 2.0 project.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseConnections(c => c.MapConnectionHandler<MqttConnectionHandler>("/mqtt", options => {
                options.WebSockets.SubProtocolSelector = MQTTnet.AspNetCore.ApplicationBuilderExtensions.SelectSubProtocol;
            }));

            //app.UseMqttEndpoint();
            app.UseMqttServer(server =>
            {
                server.Started  = async (sender, args) =>
                {
                    var msg = new MqttApplicationMessageBuilder()
                        .WithPayload("Mqtt is awesome")
                        .WithTopic("message");

                    while (true)
                    {
                        try
                        {
                            await server.PublishAsync(msg.Build());
                            msg.WithPayload("Mqtt is still awesome at "   DateTime.Now);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        finally
                        {
                            await Task.Delay(TimeSpan.FromSeconds(2));
                        }
                    }
                };
            });

            app.Use((context, next) =>
            {
                if (context.Request.Path == "/")
                {
                    context.Request.Path = "/Index.html";
                }
                if (context.Request.Path == "/publish")
                {
                    var server=app.ApplicationServices.GetRequiredService<IMqttServer>();
                    ////如果在controller中的话,也可以通过构造函数注入来获取此server,大体如下:
                    //IServiceProvider _services;
                    //public HomeController(IServiceProvider services, IHostingEnvironment env)
                    //{
                    //    _services = services;
                    //}
                    //var server = _services.GetRequiredService<IMqttServer>();
                    var msg = new MqttApplicationMessageBuilder()
                    .WithPayload("这条消息来自服务器端推送")
                    .WithTopic($"RCU/S1/Device1001");
                    server.PublishAsync(msg.Build());
                    context.Response.StatusCode = 200;
                    context.Response.Headers["Content-Type"] = "application/json";
                    context.Response.WriteAsync("发布主题成功");

                    
                }

                return next();
            });

            app.UseStaticFiles();


            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = "/node_modules",
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
            });
        }
    }
}