zoukankan      html  css  js  c++  java
  • asp.net core signalR

    一、asp.net core使用signalR入门

    1,nuget Microsoft.AspNetCore.SignalR 

    2,新建ChatHub文件

    using Microsoft.AspNetCore.SignalR;
    using System.Threading.Tasks;
    namespace SignalRDemo
    {
        public class ChatHub:Hub
        {
            public async Task SendMessage(string user,string message)
            {
                await Clients.All.SendAsync("ReceiveMessage",user,message);
            }
            
        }
    }
    ChatHub
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.AspNetCore.SignalR;
    
    namespace SignalRDemo
    {
        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.AddMvc();
    
              
                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");
                }
    
                app.UseStaticFiles();
    
    
              
                app.UseSignalR(routes=>{
                    routes.MapHub<ChatHub>("/chathub");
                });
            
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    配置Startup

    3,生成signalr.js文件

    使用npm下载signalr D:signalr> npm install @aspnet/signalr 

    将 D:signalr ode_modules@aspnetsignalrdistrowsersignalr.js 拷贝到项目中 SignalRDemowwwrootlibsignalrsignalr.js 

    4,在视图页面使用

    @{
        ViewData["Title"] = "Home Page";
    }
    
    
    <input type="text" name="" id="message" class="form-control" value="" required="required" pattern="" title="">
    
    <button type="button" class="btn btn-default" id="send" >发送</button>
    
    
    <div id="content"></div>
    
    @section Scripts{
    
        <script src="~/lib/signalr/signalr.js"></script>
        <script>
            const connection=new signalR.HubConnectionBuilder()
                                .withUrl("/chatHub")
                                .build();
    
            connection.on("ReceiveMessage",(use,message)=>{
                $("#content").append(message+"<br/>");
            });
    
            connection.start().catch(err=>{alert(err)});
    
            $("#send").click(function(){
                var msg= $("#message").val();
                connection.invoke("SendMessage","",msg).catch(err=>{alert(err)})
            });
    
    </script>
    }
    Index.cshtml

     案例下载:https://pan.baidu.com/s/1FEgPEbPZOribtYnLv-XCNQ

    二、前后端分离模式

    1,前端代码

    <html>
    <head>
    <title></title>
    </head>
    <body>
    
    
    <input type="text" name="" id="message" class="form-control" value="" required="required" pattern="" title="">
    
    <button type="button" class="btn btn-default" id="send" >发送</button>
    
    
    <div id="content"></div>
    
    
    <script src="js/jquery.js" ></script>
    <script src="js/signalr.js"></script>
    <script>
        const connection=new signalR.HubConnectionBuilder()
                                .withUrl("http://localhost:5000/chatHub")
                                .build();
    
            connection.on("ReceiveMessage",(use,message)=>{
                $("#content").append(message+"<br/>");
            });
    
            connection.start().catch(err=>{alert(err)});
    
            $("#send").click(function(){
                var msg= $("#message").val();
                connection.invoke("SendMessage","",msg).catch(err=>{alert(err)})
            });
    </script>
    </body>
    </html>
    index.html

    使用npm下载signalr

    2,后端需要配置cors

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.AspNetCore.SignalR;
    
    namespace SignalRDemo
    {
        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.AddMvc();
    
                //注册Cors的策略
                services.AddCors(options=>options.AddPolicy("CorsPolicy",builder=>{
                    builder.AllowAnyMethod()
                           .AllowAnyHeader()
                           .AllowAnyOrigin()
                           .AllowCredentials();
                }));
    
                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");
                }
    
                app.UseStaticFiles();
    
    
                //使用CorsPolicy策略的Cors
                app.UseCors("CorsPolicy");
    
                app.UseSignalR(routes=>{
                    routes.MapHub<ChatHub>("/chathub");
                });
            
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    Startup
    using Microsoft.AspNetCore.SignalR;
    using System.Threading.Tasks;
    namespace SignalRDemo
    {
        public class ChatHub:Hub
        {
            public async Task SendMessage(string user,string message)
            {
                await Clients.All.SendAsync("ReceiveMessage",user,message);
            }
            
        }
    }
    ChatHub

    案例下载:https://pan.baidu.com/s/1qcYOKuO42HltFmwP3vZgSA 

    三、Hub

    1,创建并使用Hub

    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user,message);
        }
    
        public Task SendMessageToCaller(string message)
        {
            return Clients.Caller.SendAsync("ReceiveMessage", message);
        }
    
        public Task SendMessageToGroups(string message)
        {
            List<string> groups = new List<string>() { "SignalR Users" };
            return Clients.Groups(groups).SendAsync("ReceiveMessage", message);
        }
    
        public override async Task OnConnectedAsync()
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnConnectedAsync();
        }
    
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
            await base.OnDisconnectedAsync(exception);
        }
    }
    Hub

    2,Clients对象

    ①每个实例Hub类有一个名为Clients包含服务器和客户端之间通信的以下成员:

    属性描述
    All 在所有连接的客户端上调用方法
    Caller 调用 hub 方法在客户端上调用方法
    Others 除调用的方法的客户端的所有连接客户端上调用方法

    此外,Hub.Clients包含以下方法:

    方法描述
    AllExcept 在指定的连接除外的所有连接的客户端上调用方法
    Client 在特定连接的客户端上调用方法
    Clients 在特定连接的客户端上调用方法
    Group 将消息发送到指定的组中的所有连接
    GroupExcept 将消息发送到指定的组,除非指定连接中的所有连接
    Groups 将一条消息发送到多个组的连接
    OthersInGroup 将一条消息发送到一组的连接,不包括客户端调用 hub 方法
    User 将消息发送到与特定用户关联的所有连接
    Users 将消息发送到与指定的用户相关联的所有连接

    3,将消息发送到客户端

    //将消息发送到调用此hub的客户端
    public Task SendMessageToCaller(string message)
    {
        return Clients.Caller.SendAsync("ReceiveMessage", message);
    }
    //将消息发送到指定发送的所有客户端
    public Task SendMessageToGroups(string message)
    {
        List<string> groups = new List<string>() { "SignalR Users" };
        return Clients.Groups(groups).SendAsync("ReceiveMessage", message);
    }

    4,处理消息事件

    //连接触发
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
        await base.OnConnectedAsync();
    }
    //断开连接触发
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
        await base.OnDisconnectedAsync(exception);
    }

    5,客户端处理错误

    connection.invoke("SendMessage", user, message).catch(err => console.error(err));

    四、客户端调用hub

    nuget Microsoft.AspNetCore.SignalR.Client 

    using System;
    using Microsoft.AspNetCore.SignalR.Client;
    using System.Threading.Tasks;
    using System.Threading;
    
    namespace SignalRClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("准备就绪...");
    
                HubConnection connection=new HubConnectionBuilder()
                                .WithUrl("http://localhost:5000/chatHub")
                                .Build();
    
                //连接hub
                connection.StartAsync();
                Console.WriteLine("已连接");
                
                //定义一个客户端方法ReceiveMessage
                connection.On<string,string>("ReceiveMessage",(UriParser,message)=>{
                    Console.WriteLine($"接收消息:{message}");
                });
    
                while(true)
                {
                    Thread.Sleep(1000);
                    var msg=Console.ReadLine();
                    //发送给hub的SendMessage方法
                    connection.InvokeAsync("SendMessage","",msg);
                }
    
            }
        }
    
    }
    Main

    案例下载:https://pan.baidu.com/s/1gqGNl_FPXxz0LYVozrqI5g

  • 相关阅读:
    postman获取请求响应值
    http常用状态码说明
    postman的Testing examples(测试脚本示例)
    JMeter 如何把上一个请求的结果作为下一个请求的参数 —— 使用正则提取器
    一个绿色版的正则表达式测试工具
    让TinyXML保存文件为UTF-8格式
    TinyXml2 的使用
    Apache Thrift
    解决sqlserver的sql脚本内存不足问题
    一个表的两个字段具有相同的类型。如何仅用SQL语句交换这两列的数据?
  • 原文地址:https://www.cnblogs.com/zd1994/p/9134965.html
Copyright © 2011-2022 走看看