NetCore SignalR 重連邏輯實現


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();
View Code

3-重連成功后的處理邏輯

1 //重連成功后的處理機制
2     connection.onreconnected((connectionId)=>{
3         
4         console.log("onreconnected:"+connectionId);
5         getdata();
6     });
View Code

4-連接關閉后的處理邏輯

1 //連接關閉后的處理機制
2     connection.onclose(async (error)=>{
3         var msg="close:"+error.toString();
4         console.error(msg);
5          await start();
6     });
View Code

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     };
View Code

PS:SignalR js 庫需要用 @microsoft/signalr@3.x.x 庫,不然沒有 withAutomaticReconnect 這個函數

6-參考文檔

https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1

PS:不知道是我的理解能力太差了,還是微軟的中文文檔沒寫好,折騰了一小會搞懂了,記錄一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM