一、在 ASP.NET Core 中使用 SignalR

摘要:
Hub消息处理中心publicclassTestHub:Hub{publicTestHub(){}publicasyncTaskSendMessage{#regionClient//this.Context.ConnectionId//每个连接一个connectionId表示唯一客户端//this.Clients.Client().SendAsync();//指定发送消息//this.Clients.Clients()#endregion//给多个client发消息#regionGroup//this.Clients.Group();//给某个组发消息//this.Clients.Groups()//给多个组发消息//this.Groups.AddToGroupAsync()//将指定连接加入组//this.Groups.RemoveFromGroupAsync()//将指定连接移除组#endregionawaitClients.All.SendAsync;}//上下线消息连接、断开事件//客户端连接上publicoverrideTaskOnConnectedAsync(){returnbase.OnConnectedAsync();}//客户端断开publicoverrideTaskOnDisconnectedAsync{stringconnectionId=this.Context.ConnectionId;returnbase.OnDisconnectedAsync;}}以上可以看到SignalR封装了很多常用方法,我们可以很简单的使用达到目的创建Hubs文件夹。

一、介绍

SignalR是一个用于实现实时网站的 Microsoft .NET 库。它使用多种技术来实现服务器与客户端间的双向通信,服务器可以随时将消息推送到连接的客户端。

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/signalr?tabs=visual-studio&view=aspnetcore-3.0

一、在 ASP.NET Core 中使用 SignalR第1张

二、新建Core MVC项目并安装

一、在 ASP.NET Core 中使用 SignalR第2张

三、添加 SignalR 客户端库

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

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

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

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

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

一、在 ASP.NET Core 中使用 SignalR第3张

一、在 ASP.NET Core 中使用 SignalR第4张

四、创建 SignalR 中心即操作中心。

Hub 消息处理中心

public classTestHub : Hub
{
    publicTestHub()
    {
    }
    public async Task SendMessage(string message, stringname)
    {
        #region Client
        //this.Context.ConnectionId                 //每个连接一个connectionId  表示唯一客户端
        //this.Clients.Client().SendAsync();        //指定发送消息
        //this.Clients.Clients()        
        #endregion             //给多个client发消息
        #region Group
        //this.Clients.Group();                     //给某个组发消息
        //this.Clients.Groups()                     //给多个组发消息
        //this.Groups.AddToGroupAsync()             //将指定连接加入组
        //this.Groups.RemoveFromGroupAsync()        //将指定连接移除组 
        #endregion
        await Clients.All.SendAsync("onMsg", DateTime.Now, message);
    }
    //上下线消息  连接、断开事件
    //客户端连接上
    public overrideTask OnConnectedAsync()
    {
        return base.OnConnectedAsync();
    }
    //客户端断开
    public overrideTask OnDisconnectedAsync(Exception exception)
    {
        string connectionId = this.Context.ConnectionId;
        return base.OnDisconnectedAsync(exception);
    }
}

以上可以看到SignalR封装了很多常用方法(发送指定消息、群发...),我们可以很简单的使用达到目的

创建 Hubs 文件夹 。

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

一、在 ASP.NET Core 中使用 SignalR第5张

一、在 ASP.NET Core 中使用 SignalR第6张

usingMicrosoft.AspNetCore.SignalR;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Threading.Tasks;
namespaceBan.Hubs
{
    public classChatHub:Hub 
    {
        /// <summary>
        ////服务端方法 发送消息--发送给所有连接的客户端
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string user,stringmessage)
        {
            //ReceiveMessage 为客户端方法,让所有客户端调用这个方法
            await Clients.All.SendAsync("ReceiveMessage",user,message);
        }
        /// <summary>
        ///客户端连接的时候调用
        /// </summary>
        /// <returns></returns>
        public overrideTask OnConnectedAsync()
        {
            Trace.WriteLine("客户端连接成功");
            return base.OnConnectedAsync();
        }//所有链接的客户端都会在这里
        /// <summary>
        ///连接终止时调用。
        /// </summary>
        /// <returns></returns>
        public overrideTask OnDisconnectedAsync(Exception exception)
        {
            Trace.WriteLine("连接终止");
            return base.OnDisconnectedAsync(exception);
        }
    }
}

六、配置 SignalR

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

startupConfigureServices方法内部添加SignalR服务services.AddSignalR();Configure中配置具体的Hub(路由器、中转):

    app.UseSignalR(routes =>
    {
        routes.MapHub<TestHub>("/testHub");     //可以多个map
});
    app.UseMvc();           //注意UseSignalR需要在UseMvc()之前

这样SignalR服务器端就开发完成了,网页、Java、.Net客户端都可以连接的

一、在 ASP.NET Core 中使用 SignalR第7张

usingMicrosoft.AspNetCore.Builder;
usingMicrosoft.AspNetCore.Hosting;
usingMicrosoft.AspNetCore.Http;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Configuration;
usingMicrosoft.Extensions.DependencyInjection;
using test.Hubs; //3、引用 处理客户端 - 服务器通信的高级管道
namespacetest
{
    public classStartup
    {
        publicStartup(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 voidConfigureServices(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_1);
            services.AddSignalR();//1、添加服务
}
        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public voidConfigure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes => //2、引用
{
                routes.MapHub<ChatHub>("/chatHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

七、添加 SignalR 客户端代码(创建index控制器和视图)

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport"content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div class="container">
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-6">&nbsp;</div>
            <div class="col-6">
                User..........<input type="text"id="userInput" />
                <br />
                Message...<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 type="text/javascript">
        "use strict";
        varconnection = newsignalR.HubConnectionBuilder().withUrl("/chatHub").build();
        //在建立连接之前禁用发送按钮
document.getElementById("sendButton").disabled = true;
        //接受消息
connection.on("ReceiveMessage", function(user, message) {
            varmsg =message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
            varencodedMsg =user + "says " +msg;
            varli =document.createElement("li");
            li.textContent =encodedMsg;
            document.getElementById("messagesList").appendChild(li);
        });
        //开始链接
connection.start().then(function() {
            document.getElementById("sendButton").disabled = false;
        }).catch(function(err) {
            returnconsole.error(err.toString());
        });
        //发送消息
document.getElementById("sendButton").addEventListener("click", function(event) {
            varuser =document.getElementById("userInput").value;
            varmessage =document.getElementById("messageInput").value;
            connection.invoke("SendMessage", user, message).catch(function(err) {
                returnconsole.error(err.toString());
            });
            event.preventDefault();
        });
    </script>
</body>
</html>

一、在 ASP.NET Core 中使用 SignalR第8张

Controller中调用SignalR服务

在构造函数注入IHubContext<>就可以直接使用了,非常方便:

   private readonly IHubContext<TestHub>_hubContext;
    public HomeController(IHubContext<TestHub>hubContext)
    {
        _hubContext =hubContext;
    }
    public async Task<IActionResult>Notify()
    {
        //拿不到当前Hub的clientId  线程是唯一的
        await _hubContext.Clients.All.SendAsync("onMsg", "from controller msg");
        returnOk();
    }

免责声明:文章转载自《一、在 ASP.NET Core 中使用 SignalR》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇oracle正则表达式regexp_like的用法详解C#中JSON字符串中的转义字符下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

单体架构、SOA、微服务

1、单体架构 2、单体架构的拆分 3、SOA与微服务的区别 4、微服务的优缺点 5、微服务的消息 6、服务集成 7、数据的去中心化 一、单体架构 Web应用程序发展的早期,大部分web工程是将所有的功能模块(service side)打包到一起并放在一个web容器中运行,很多企业的Java应用程序打包为war包。其他语言(Ruby,Python或者C++)...

VC++ 定时器使用总结

VC++    WM_TIMER   定时器使用方法       在编程时,会经常使用到定时器。使用定时器的方法比较简单,通常告诉Windows一个时间间隔,然后WINDOWS以此时间间隔周期性触发程序。通常有两种方法来实现:发送WM_TIMER消息和调用应用程序定义的回调函数。   1.1 用WM_TIMER来设置定时器   先请看SetTimer这个A...

RPC

背景:公司提供给第三方的数据传输接口一直是以Hessian的协议进行发布的,但是由于交通车辆通行数据量较大,导致第三方反应出现数据延迟的情况或者连接超时的情况,所以需要更换Hessian,换成性能更高的Thrift协议 区别: Hessian  Thrift 优点 1、简单易用,面向接口,通过接口暴露服务,jar包只有200、300k,不需要配置...

uni-app 基本配置pages,json

{ // 打开页面的路径 "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages // 在第一位的事默认打开的页面 { "path": "pages/message/messa...

相似度度量计算

看到很多地方在用这个, 就 总结一下:      相似度度量(Similarity),即计算个体间的相似程度,相似度度量的值越小,说明个体间相似度越小,相似度的值越大说明个体差异越大。      对于多个不同的文本或者短文本对话消息要来计算他们之间的相似度如何,一个好的做法就是将这些文本中词语,映射到向量空间,形成文本中文字和向量数据的映射关系,通过计算几...

springCloud组件详细解析

1 springcloud有哪些组件?  Eureka 服务注册中心  Ribbon 负载均衡  Zuul 网关  Fegin 客户端Web  Hsytri 熔断器  Bus 消息总线  Config 统一配置中心 2 什么是自我保护模式  springCould的服务注册中心会监控微服务的心跳。如果检测到心跳,那么这个时候服务注册中心进入自我保护模式...