Dot-Net-Core
.NET Core SignalR,伺服器超時/重新連接問題
我在我的 MVC 解決方案中編寫了一個 SignalR 集線器,並帶有一個從視圖連接的 Javascript 客戶端。
連接的目的是從伺服器接收對牆板的更改。這必須幾乎立即發生並且需要終生連接,因為網頁是在螢幕上執行而沒有直接的 PC 訪問。
到目前為止,SignalR 連接工作了幾個小時,然後才出現錯誤。
我得到的錯誤是
Error: Connection disconnected with error 'Error: Server timeout elapsed without receiving a message form the server.'. Failed to load resource: net::ERR_CONNECTION_TIMED_OUT Warning: Error from HTTP request. 0: Error: Failed to complete negotiation with the server: Error Error: Failed to start the connection: Error Uncaught (in promise) Error at new HttpError (singlar.js:1436) at XMLHttpRequest.xhr.onerror (singalr.js:1583)我的客戶程式碼
let connection = new signalR.HubConnectionBuilder() .withUrl("/wbHub") .configureLogging(signalR.LogLevel.Information) .build(); connection.start().then(function () { connection.invoke("GetAllWallboards").then(function (wallboard) { for (var i = 0; i < wallboard.length; i++) { displayWallboard(wallboard[i]); } startStreaming(); }) }) connection.onclose(function () { connection.start().then(function () { startStreaming(); }) }) function startStreaming() { connection.stream("StreamWallboards").subscribe({ close: false, next: displayWallboard }); }集線器程式碼:
public class WallboardHub : Hub { private readonly WallboardTicker _WallboardTicker; public WallboardHub(WallboardTicker wallboardTicker) { _WallboardTicker = wallboardTicker; } public IEnumerable<Wallboard> GetAllWallboards() { return _WallboardTicker.GetAllWallboards(); } public ChannelReader<Wallboard> StreamWallboards() { return _WallboardTicker.StreamWallboards().AsChannelReader(10); } public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception exception) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnDisconnectedAsync(exception); } }問題1:我處理重新連接的方式是否正確?從錯誤中感覺像是
.onclose作品,但它只嘗試一次?無論如何在顯示錯誤之前嘗試 x min 嗎?問題 2:重新載入網站使連接再次工作,是否有可能在 signalR 連接錯誤時刷新瀏覽器?
我有同樣的問題(問題 1),我解決了這個問題:
const connection = new SignalR.HubConnectionBuilder() .withUrl("/hub") .configureLogging(SignalR.LogLevel.Information) .build(); connect(connection); async function connect(conn){ conn.start().catch( e => { sleep(5000); console.log("Reconnecting Socket"); connect(conn); } ) } connection.onclose(function (e) { connect(connection); }); async function sleep(msec) { return new Promise(resolve => setTimeout(resolve, msec)); }每 5 秒嘗試重新連接一次,但我不知道這是否是正確的方法。