• SignalR系列文章02---netCoreMvc创建Demo


    1、  新建.net core MVC项目,并引入nuget包

    2、  添加客户端库

    3、  修改startUp.cs文件,增加services.AddSignalR();和endpoints.MapHub<ServerHub>("/serverHub");

     public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddSignalR();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapHub<ServerHub>("/serverHub");
                });
            }
        }

    4、  新增ServerHub类

    public class ServerHub:Hub
        {
            public async Task Send(string message)
            {
                await Clients.All.SendAsync("sendMessage", message);
            }
        }

    5、  在Home/index.cshtml文件中加入如下的代码

    @{
        ViewBag.Title = "聊天窗口";
    }
    
    <h2>Chat</h2>
    
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    
    @section scripts
    {
        <!--引用SignalR库. -->
        <script src="~/lib/signalr/signalr.min.js"></script>
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
    
        <script>
            $(function () {
    
                let hubUrl = 'https://localhost:44360/serverHub';
                let hubConnection = new signalR.HubConnectionBuilder().withUrl(hubUrl).build();
    
                $('#sendmessage').click(function () {
                    hubConnection.invoke("Send", $('#message').val());
                    // 清空输入框信息并获取焦点
                    $('#message').val('').focus();
                });
                //服务器回调方法
                hubConnection.on("sendMessage", function (data) {
                    // 向页面添加消息
                    $('#discussion').append('<li><strong>' + htmlEncode(data)
                        + '</strong></li>');
                })
    
                hubConnection.start();
    
    
            });
    
            // 为显示的消息进行Html编码
            function htmlEncode(value) {
                var encodedValue = $('<div />').text(value).html();
                return encodedValue;
            }
        </script>
    }

    6、  运行效果

  • 相关阅读:
    圆圈中最后剩下的数字 【微软面试100题 第十八题】
    第一个只出现一次的字符 【微软面试100题 第十七题】
    从上往下打印二叉树 【微软面试100题 第十六题】
    二叉树的镜像 【微软面试100题 第十五题】
    和为s的两个数字 【微软面试100题 第十四题】
    链表中倒数第k个结点 【微软面试100题 第十三题】
    求1+2+...+n 【微软面试100题 第十二题】
    求二叉树中结点的最大距离 【微软面试100题 第十一题】
    翻转句子中单词的顺序 【微软面试100题 第十题】
    二叉搜索树的后序遍历序列 【微软面试100题 第九题】
  • 原文地址:https://www.cnblogs.com/zhengwei-cq/p/15429147.html
Copyright © 2020-2023  润新知