我有一个 SignalR 服务器(一个 Web 应用程序)和一个客户端(一个控制台应用程序)。
我希望我的客户端在我的服务器的 IIS 重新启动/关闭或服务器简单地重新启动/关闭时得到通知。
这可能吗?
最佳答案
你可以这样做
var connection = new HubConnection(hubUrl);
if (configureConnection != null)
configureConnection(connection);
var proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Reconnected += reconnected;
其他事件是
- Reconnecting - 在连接关闭后尝试重新连接时触发
- 关闭 - 连接断开时触发
更新:
Closed
将在重新连接失败时调用(当 IIS 关闭的时间超过重新连接超时所接受的时间时)。
这意味着您应该使用 connection.Start()
从 Close 事件重新连接,当它失败时,Closed 事件将被再次调用,并且可以使用 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;
}
}
关于c# - 通知 SignalR 客户端 IIS 重启/关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328863/