zoukankan      html  css  js  c++  java
  • [SignalR]

    框架

    后端服务:.Net Core 3.1 WebAPI
    前端页面:.Net Core 3.1 MVC

    服务端

    1. 跨域配置(CORS

    使用 Nuget 安装 Microsoft.AspNet.WebApi.Cors

    2. 项目配置(Startup)

    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.AddControllers();
            services.AddSignalR();
            services.AddCors(op => { op.AddPolicy("cors", set => { set.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });
        }
    
        // 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();
            }
    
            app.UseCors("cors");
            app.UseRouting();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<NotificationHub>("/NotificationHub");
            });
        }
    }

    3. 业务逻辑,主动推送消息

    [ApiController]
    [Route("[controller]")]
    public class NotificationController : ControllerBase
    {
    	private readonly ILogger<NotificationController> _logger;
    	private readonly IHubContext<NotificationHub> _hubContext;
    
    	public NotificationController(ILogger<NotificationController> logger, IHubContext<NotificationHub> hubContext)
    	{
    		_logger = logger;
    		_hubContext = hubContext;
    	}
    
    	[HttpGet]
    	public string Get()
    	{
    		var message = new NotificationModel { Gid = Guid.NewGuid() };
    		var json = Newtonsoft.Json.JsonConvert.SerializeObject(message);
    		//_hubContext.Clients.All.SendAsync("NotificationCenter", json);
    		_hubContext.Clients.Group("5f3b332bbdae582770fb5ec9").SendAsync("NotificationCenter", json);
    		return Convert.ToString(json);
    	}
    }
    
    public class NotificationModel
    {
    	public Guid Gid { get; set; }
    }
    

    客户端配置

    1. 为解决方案添加 SignalR 客户端库

    2. 业务逻辑,接收推送过来的消息

    "use strict";
    
    var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:7370/NotificationHub").build();
    
    connection.start().then(function () {
        var groupId = "5f3b332bbdae582770fb5ec9";
        connection.invoke("AddToGroup", groupId);
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    connection.on("NotificationCenter", function (json) {
        var _obj = JSON.parse(json);
        var _div = document.createElement('div');
        _div.innerText = _obj.Gid;
        document.getElementById("messagesList").appendChild(_div);
    });

    范例演示

    指定推送对象

    所有连接的客户。
    Clients.All.addContosoChatMessageToPage(name, message);
    
    只有呼叫客户端。
    Clients.Caller.addContosoChatMessageToPage(name, message);
    
    除呼叫客户端外的所有客户端。
    Clients.Others.addContosoChatMessageToPage(name, message);
    
    由连接ID标识的特定客户端。
    Clients.Client(Context.ConnectionId).addContosoChatMessageToPage(name, message);
    
    除了指定的客户端的所有连接的客户端,由连接ID标识。
    Clients.AllExcept(connectionId1, connectionId2).addContosoChatMessageToPage(name, message);
    
    在指定的组中的所有连接的客户端。
    Clients.Group(groupName).addContosoChatMessageToPage(name, message);
    
    指定组中除指定客户端外的所有已连接客户端,由连接ID标识。
    Clients.Group(groupName, connectionId1, connectionId2).addContosoChatMessageToPage(name, message);
    
    指定组中除呼叫客户端外的所有已连接客户端。
    Clients.OthersInGroup(groupName).addContosoChatMessageToPage(name, message);
    
    由userId标识的特定用户。
    Clients.User(userid).addContosoChatMessageToPage(name, message);
    (默认情况下,这是IPrincipal.Identity.Name可以通过向全局主机注册IUserIdProvider的实现来更改的。)
    
    连接ID列表中的所有客户端和组。
    Clients.Clients(ConnectionIds).broadcastMessage(name, message);
    
    组ID列表中的所有组。
    Clients.Groups(GroupIds).broadcastMessage(name, message);
    
    用户名标识的客户端。
    Clients.Client(username).broadcastMessage(name, message);
    
    用户名列表对应的所有客户端(在SignalR 2.1中引入)。
    Clients.Users(new string[] { "myUser", "myUser2" }).broadcastMessage(name, message);

    参考资料

    Tutorial: Get started with ASP.NET Core SignalR
    https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio

    Manage users and groups in SignalR
    https://docs.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-3.1#groups-in-signalr

    ASP.NET SignalR 系列教程
    https://www.cnblogs.com/fei686868/tag/SignalR/

    ASP.NET Core SignalR CORS 跨域问题
    https://www.cnblogs.com/IT-Ramon/p/12156832.html

    signalR服务端调用客户端方法说明
    https://blog.csdn.net/niuc321/article/details/80348108

  • 相关阅读:
    2019 学霸君java面试笔试题 (含面试题解析)
    2019 大众书网Java面试笔试题 (含面试题解析)
    2019 中细软java面试笔试题 (含面试题解析)
    2019 企叮咚java面试笔试题 (含面试题解析)
    js 去掉数组对象中的重复对象
    canvas霓虹雨
    nvm的安装
    socket.io 中文文档
    Nginx(三)------nginx 反向代理
    github入门到上传本地项目
  • 原文地址:https://www.cnblogs.com/jinzesudawei/p/13580553.html
Copyright © 2011-2022 走看看