服務器端引入包 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");});
寫一個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 });}}
控制器中模擬觸發后端推送請求
[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 請求已接收并處理,但還沒有處理完成 }}
?
?
消息推送服務、?
?
?
?
?
android消息推送??
?