有没有办法检查SignalR服务器/集线器是否处于活动/启动/准备/通过服务器端代码接受连接?

我有一个控制台应用程序连接到SignalR Hub并发送消息等。工作完全正常。

今天,当我启动我的控制台应用程序时,我忘了 – 也 – 启动我的SignalR集线器(因此没有集线器,活动和接受/发送消息)。

当然,我得到了一个低级连接错误:

服务器正在积极拒绝连接等…

有没有办法可以检查Hub是否在线,活动并接受连接? 或者是使用try / catch的唯一方法,并假设任何捕获,它是脱机的?

这是我的示例代码:

_hubConnection.Start().ContinueWith(task => { if (task.IsFaulted) { WriteLine( string.Format(" !!! There was an error opening the connection:{0}", task.Exception.GetBaseException()), ConsoleColor.Red); } else { WriteLine(" * Connected to the Hub @ http://localhost:80"); } }).Wait(); 

干杯!

如果使用持久连接,则可以更容易地找出它是否已连接。 如果你想使用Hub而不是Persistent Connection,我不知道如何检查。

下面的示例使用持久连接在start()之前检查连接。

持续连接

 public class HubPersistentConnection : PersistentConnection { protected override Task OnConnected(IRequest request, string connectionId) { return Connection.Send(connectionId, "It's connected."); } // Override more method here } 

jQuery的

 $(function () { var _hubConnection= $.connection('/echo'); _hubConnection.received(function (data) { //Do something }); _hubConnection.start().done(function () { //Do something }); }); 

在启动文件中映射持久连接

 app.MapSignalR("/echo");