1-配置連接配接
1 var connection = new signalR.HubConnectionBuilder()
2 .withUrl("http://localhost:5000/doopstream")
3 //重連函數,參數是重連間隔時間,機關毫秒
4 .withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000])
5 .configureLogging(signalR.LogLevel.Information)
6 .build();
View Code
2-啟動邏輯
1 //啟動子產品
2 async function start(){
3 connection.start().then(()=>getdata()).catch(err => {
4 var msg="strat:"+err.toString();
5 console.error(msg);
6 setTimeout(()=>start(),5000);
7 });
8 }
9 //觸發啟動
10 start();
3-重連成功後的處理邏輯
1 //重連成功後的處理機制
2 connection.onreconnected((connectionId)=>{
3
4 console.log("onreconnected:"+connectionId);
5 getdata();
6 });
4-連接配接關閉後的處理邏輯
1 //連接配接關閉後的處理機制
2 connection.onclose(async (error)=>{
3 var msg="close:"+error.toString();
4 console.error(msg);
5 await start();
6 });
5-資料接收處理邏輯
1 /接收資料邏輯
2 function getdata() {
3 console.log("connected");
4 connection.invoke("Subscribe", 'test').catch(err => console.error(err.toString()));
5 connection.on("Receive", function (ch, message) {
6 console.log(message);
7 var p = document.createElement("p");
8 p.innerHTML = ch + '#' + message;
9 var div = document.getElementById("div");
10 div.appendChild(p);
11 });
12 };
PS:SignalR js 庫需要用 @microsoft/[email protected] 庫,不然沒有 withAutomaticReconnect 這個函數
6-參考文檔
https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1
PS:不知道是我的了解能力太差了,還是微軟的中文文檔沒寫好,折騰了一小會搞懂了,記錄一下
漫漫人生,唯有激流勇進,不畏艱險,奮力拼搏,方能中流擊水,抵達光明的彼岸