0

我有一个连接到 SignalR Hub 并发送消息等的控制台应用程序。工作得很好。

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

当然,我遇到了低级连接错误:

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

有什么方法可以检查集线器是否在线、活动并接受连接?或者是使用 try/catch 并假设任何 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();

干杯!

4

1 回答 1

1

如果您使用持久连接,您会更容易确定它是否已连接。如果您想使用集线器而不是持久连接,我不确定如何检查。

下面的示例使用持久连接在 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<HubPersistentConnection>("/echo");
于 2013-11-11T02:07:29.380 回答