.netcore signalR 实时消息推送

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

 1 <template>
 2   <div><p>测试SignalR后台推送消息</p><p>ConnectionId {{connectId}}</p> {{retData}}</div>
 3 </template>
 4 
 5 <script>
 6 import * as signalR from '@aspnet/signalr'
 7     export default {
 8         data() {
 9             return {
10                 retData: '',
11                 connection: "",
12                 connectId:""
13             }
14         },
15         methods: {
16         },
17         created: function () {
18             let thisVue = this;
19            
20            //1 客户端创建连接
21             let connection = new signalR.HubConnectionBuilder()
22                   .withUrl('/api/chathub')
23                   //.withUrl('/chathub',signalR.HttpTransportType.WebSockets)//手动指定传输方式, 请在withUrl()方法的第二个参数
24                   .build();
25 
26             //2 监听服务器端发送的方法
27             connection.on('someFunc', function (obj) {
28                 thisVue.retData =obj.radom ;
29             });
30             connection.on('receiveupdate', function (obj) {
31                 thisVue.retData =obj ;
32             });
33             connection.on('getconnectId', function (obj) {
34                 thisVue.connectId = obj.connectId
35             });
36             connection.on('finsied', function () {
37                 connection.stop();
38                 thisVue.retData = "finished"
39             });
40 
41             //3 开始通信,并调用服务器端方法GetLatestCount
42             connection.start()
43                       //.then(() => {connection.invoke('GetLatestCount', 1);thisVue.retData = "started"})
44                       .catch(err => console.error(err.toString()));
45         }
46     }
47 </script>
前端代码

startup.cs添加代码

services.AddSignalR();
 

app.UseSignalR(route =>
            {
                route.MapHub<ChatHub>("/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<ChatHub> _hubContext;
        public ChatHubController(IHubContext<ChatHub> hubContext)
        {
            _hubContext = hubContext;
        }

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

 

 

 

 

 

 

 

 

 

posted @ 2019-05-20 14:29  胡椒面  阅读(1670)  评论(2编辑  收藏  举报