.netcore signalR 实时消息推送

服务器端引入包 Install-Package Microsoft.AspNetCore.SignalR
客户端引入包  npm install @aspnet/signalr

 1 
 4 
 5 
前端代码

startup.cs添加代码

services.AddSignalR();
 

app.UseSignalR(route =>
            {
                route.MapHub("/api/chathub");
            });
Startup

写一个Hub中心代码,继承自Hub类

引入包 

public class ChatHub : Hub
    {
        public string connectionId = "";
        //客户端调用服务器端的GetLatestCount方法
        //服务器端调用客户端的receiveupdate方法(前端监听)
        public async Task GetLatestCount(string random)
        {
            int count = 0;
            do
            {
                count++;
                Thread.Sleep(500);
                await Clients.All.SendAsync("receiveupdate", random + " " + count);
            } while (count < 10);

            await Clients.All.SendAsync("finsied");
        }

        public override async Task OnConnectedAsync()
        {
            var connectionId = Context.ConnectionId;
            //await Groups.AddToGroupAsync(connectionId, "mygroup");
            //await Groups.RemoveFromGroupAsync(connectionId, "mygroup");
            //await Clients.Group("mygroup").SendAsync("someFunc", new { radom = "0.0" });

            await Clients.Client(connectionId).SendAsync("getconnectId", new { connectId = connectionId });
        }
    }
ChatHub

控制器中模拟触发后端推送请求

 [Produces("application/json")]
    [Route("api/chat")]
    public class ChatHubController : Controller
    {
        private readonly IHubContext _hubContext;
        public ChatHubController(IHubContext hubContext)
        {
            _hubContext = hubContext;
        }

        //测试消息实时推送
        [HttpPost]
        public async Task Post()
        {
            await _hubContext.Clients.All.SendAsync("someFunc", new { radom = new Random().Next(10,10000)});
            return Ok();// Accepted(1);//202 请求已接收并处理,但还没有处理完成
        }
    }
ChatHubController

 

 

 

 

 

.netcore signalR 实时消息推送_第1张图片

 

 

 

.netcore signalR 实时消息推送_第2张图片

 

转载于:https://www.cnblogs.com/langhaoabcd/p/10893979.html

你可能感兴趣的:(.netcore signalR 实时消息推送)