如何使用SignalR事件以正确的方式保持连接活动?

我正在使用SignalR,ASP.NET和C#开发实时客户端 – 服务器应用程序。 我使用localhost作为主机和VS2013。

我的问题是:

  1. 为什么我关闭服务器,在Web客户端上发生“ 重新连接 ”事件?

  2. “断开”事件仅在40秒以后发生。 如何减少这个时间?

  3. 我需要客户端在启动时连接到服务器。 “重新连接”事件应仅在固定间隔内发生。 如果“重新连接”间隔时间结束,则客户端应作为新客户端连接。 如何归档这个目标?

最后,我想问一下 – 如何以正确的方式使用SignalR 保持连接?

我正在使用此代码:

C#

public override Task OnDisconnected() { clientList.RemoveAt(nIndex); Console.WriteLine("Disconnected {0}\n", Context.ConnectionId); return (base.OnDisconnected()); } public override Task OnReconnected() { Console.WriteLine("Reconnected {0}\n", Context.ConnectionId); return (base.OnReconnected()); } 

使用Javascript

 $.connection.hub.reconnected(function () { // Html encode display name and message. var encodedName = $('
').text("heartbeat").html(); var now = new Date(); // Add the message to the page. $('#discussion').append('Reconnected to server: ' + now + '
'); }); $.connection.hub.disconnected(function () { // Html encode display name and message. var encodedName = $('
').text("heartbeat").html(); var now = new Date(); // Add the message to the page. $('#discussion').append('Disconnected from server: ' + now + '
'); });

连接输出后:

 message received from server : Fri Feb 21 2014 10:53:02 

关闭服务器输出后:

 Reconnected to server: Fri Feb 21 2014 10:53:22 <-- Why, if i close server ??? Disconnected from server: Fri Feb 21 2014 10:53:53 <-- Why 40+ seconds after the server is closed ? 

1. 关闭服务器后,在Web客户端上发生“ 重新连接 ”事件,并且仅在发生“ 断开连接 ”事件后才会发生。 为什么?

SignalR无法区分关闭服务器和重新启动服务器。 因此,当服务器关闭时,客户端将开始尝试重新连接,以防服务器实际重新启动。

2.“断开连接”在未知“重新连接”后30秒内发生。 如何减少这个时间?

可以通过DisconnectTimeout属性修改此30秒超时。

3.我需要客户端在启动时连接到服务器。 “重新连接”应仅在固定间隔内发生。 如果“重新连接”间隔时间结束,则客户端应连接为新客户端。

您应该在断开连接的事件上启动连接 ,最好在超时后启动连接 ,以便在重新启动时减少服务器负载。

 $.connection.hub.disconnected(function() { setTimeout(function() { $.connection.hub.start(); }, 5000); // Re-start connection after 5 seconds }); 

SignalR文章中的整个理解和处理连接生命周期事件可能与您的问题有关。