zoukankan      html  css  js  c++  java
  • .net core 实时通讯

           最近在搞一个web平台的在线客服,用来反馈各地市县区对平台使用的意见,有利于平台的升级和改进。对于B/S这种模式,前后端分离好像并不是太明显。以前还真没搞过这种形式的。在网上搜了一下,有点让人无语,有的写写一半留一半,引入的东西可能自己都没搞清楚。我看了许多,实在头疼。最后我看了一下微软的官方文档,按照官方给的步骤,一步一步来,一会就能搞定了。

          实现实时应用功能,要用到SignalR

          下面我就一步一步的来把这个过程操作完,做个小Demo

          首先新建一个工程,我建的是.net core 2.2 (注意一定要看版本,不同版本实现方式是有一点差异的,我看了.net core 3.1的,首先startup文件里的内容就所改变了。

         

      

    添加 SignalR 客户端库

    • 在“解决方案资源管理器”中,右键单击项目,然后选择“添加”>“客户端库” 。

    • 在“添加客户端库” 对话框中,对于“提供程序” ,选择“unpkg” 。

    • 对于“库” ,输入 @microsoft/signalr@3,然后选择不是预览版的最新版本。

    • 选择“选择特定文件” ,展开“dist/browser” 文件夹,然后选择“signalr.js” 和“signalr.min.js” 。

    • 将“目标位置” 设置为 wwwroot/lib/signalr/ ,然后选择“安装” 。

    LibMan 创建 wwwroot/lib/signalr 文件夹并将所选文件复制到该文件夹

    查看wwwroot/lib/signalr 会出现你引入的文件。

    创建 SignalR 中心

    中心是一个类,用作处理客户端 - 服务器通信的高级管道。

    • 在 项目文件夹中,创建 Hubs 文件夹 。

    • 在 Hubs 文件夹中,使用以下代码创建 ChatHub.cs 文件 :

         

    public class ChatHub : Hub
        {
            public async Task SendMessage(string user, string message)
            {
                await Clients.All.SendAsync("ReceiveMessage", user, message);
            }
        }

    hatHub 类继承自 SignalR Hub 类。 Hub 类管理连接、组和消息。

    可通过已连接客户端调用 SendMessage,以向所有客户端发送消息。 本教程后面部分将显示调用该方法的 JavaScript 客户端代码。 SignalR 代码是异步模式,可提供最大的可伸缩性。

    配置 SignalR

    必须配置 SignalR 服务器,以将 SignalR 请求传递到 SignalR。

      注意:标红的代码就是配置的SignalR 服务

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    namespace WebApplication4
    {
        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.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.AddSignalR();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment 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.UseCookiePolicy();
                app.UseSignalR(routes =>
                {
                    routes.MapHub<Hubs.ChatHub>("/chatHub");
                });
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    添加 SignalR 客户端代码

    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div class="container">
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-6">&nbsp;</div>
            <div class="col-6">
                用户名<input type="text" id="userInput" />
                <br />
                   内容<input type="text" id="messageInput" />
                <input type="button" id="sendButton" value="Send Message" />
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <hr />
            </div>
        </div>
        <div class="row">
            <div class="col-6">&nbsp;</div>
            <div class="col-6">
                <ul id="messagesList"></ul>
            </div>
        </div>
    </div>
    <script src="~/lib/signalr/dist/browser/signalr.js"></script>
    <script>
        var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    
        //Disable send button until connection is established
        document.getElementById("sendButton").disabled = true;
    
        connection.on("ReceiveMessage", function (user, message) {
            var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
            var encodedMsg = user + " says " + msg;
            var li = document.createElement("li");
            li.textContent = encodedMsg;
            document.getElementById("messagesList").appendChild(li);
        });
    
        connection.start().then(function () {
            document.getElementById("sendButton").disabled = false;
        }).catch(function (err) {
            return console.error(err.toString());
        });
    
        document.getElementById("sendButton").addEventListener("click", function (event) {
            var user = document.getElementById("userInput").value;
            var message = document.getElementById("messageInput").value;
            connection.invoke("SendMessage", user, message).catch(function (err) {
                return console.error(err.toString());
            });
            event.preventDefault();
        });
    </script>

    然后可以编译运行了。

    这样实时应用就实现了,是不是很简单?

  • 相关阅读:
    web前端的发展态势
    AngularJs 简单入门
    css代码优化篇
    git提交报错:Please make sure you have the correct access rights and the repository exists.
    Activiti工作流框架学习
    遍历map集合的4种方法
    js设置日期、月份增加减少
    Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    webservice_rest接口_学习笔记
    相互匹配两个list集合+动态匹配${}参数
  • 原文地址:https://www.cnblogs.com/zpy1993-09/p/13108230.html
Copyright © 2011-2022 走看看