我有一个SignalR服务器 (一个Web应用程序) 和一个客户端 (一个控制台应用程序)。
我希望我的客户端在我的服务器的IIS重新启动/关闭或服务器简单地重新启动/关闭时得到通知。
这是可能的吗?
我有一个SignalR服务器 (一个Web应用程序) 和一个客户端 (一个控制台应用程序)。
我希望我的客户端在我的服务器的IIS重新启动/关闭或服务器简单地重新启动/关闭时得到通知。
这是可能的吗?
var connection = new HubConnection(hubUrl);
if (configureConnection != null)
configureConnection(connection);
var proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Reconnected += reconnected;
其他事件包括:
更新:
已关闭
将在重新连接失败时被调用(当IIS宕机时间超过重新连接超时时间)。
这意味着您应该从已关闭
事件重新连接,使用connection.Start()
,当它失败时,可以再次通过connection.Start()
重试,并再次调用已关闭
事件。
以下是使用我的代码示例,它将在应用程序启动时存活,即使 IIS 宕机或在运行时停止也是如此。
public class HubProxyFactory : IHubProxyFactory
{
public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted, Action reconnected, Action<Exception> faulted, Action connected)
{
var connection = new HubConnection(hubUrl);
if (configureConnection != null)
configureConnection(connection);
var proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Reconnected += reconnected;
connection.Error += faulted;
var isConnected = false;
Action start = () =>
{
Task.Factory.StartNew(() =>
{
try
{
connection.Start().Wait();
if(isConnected)
reconnected();
else
{
isConnected = true;
onStarted(proxy);
connected();
}
}
catch(Exception ex)
{
faulted(ex);
}
});
};
connection.Closed += start;
start();
return proxy;
}
}
目前我唯一的解决方案(虽然很印度式)是尝试在特定时间间隔内重新连接到SignalR服务器。
HubConnection _connection = new HubConnection(Properties.Settings.Default.UserLoginDataSource);
IHubProxy _hub;
void TryConnectingDataSource()
{
try
{
_connection.Stop();
_connection.Dispose();
_connection = new HubConnection(Properties.Settings.Default.UserLoginDataSource);
_connection.StateChanged += connection_StateChanged;
_hub = _connection.CreateHubProxy("myHub");
_connection.Start().Wait();
if (_connection.State == ConnectionState.Connected)
{
_hub.On("myHubCallback", new Action<Dictionary<string, Entities.Permissions.UserTypes>>(GetUserLoginList));
_hub.Invoke("myHubMethod");
}
}
catch (Exception x)
{
EventLogger.LogError(x);
}
}
如果我被 catch 到了,那通常意味着连接出了问题,很可能是 ISS 崩溃了。