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>

    然后可以编译运行了。

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

  • 相关阅读:
    js 判断所选时间(或者当前时间)是否在某一时间段的实现代码
    js 日期比较大小,js判断日期是否在区间内,js判断时间段是否在另外一个时间段内
    tfs 2013 利用 web deploy 完成asp.net站点自动发布
    Web Deploy 服务器安装设置与使用
    MD5加密解密类(asp.net)&使用MD5过时处理
    C# 中Web.config文件的读取与写入
    巧用Ajax的beforeSend 提高用户体验
    一个通用的分页类
    EventSource 对象用于接收服务器发送事件通知,是网页自动获取来自服务器的更新
    Java WebSockets
  • 原文地址:https://www.cnblogs.com/zpy1993-09/p/13108230.html
Copyright © 2011-2022 走看看