Is there a way to check if a SignalR server/hub is active/up/ready/accepting connections via server side code?

懵懂的女人 提交于 2019-12-10 11:59:23

问题


I have a console application that connects to SignalR Hub and sends messages, etc. Works perfectly fine.

Today, when I started my console app, I forgot to -also- start my SignalR hub (so there was no hub up, active and accepting/sending messages).

Of course, I got a low level connect error:

Server is actively refusing connections, etc...

Is there a way that I can check to see if the Hub is online, active and accepting connections? Or is the only way to use a try/catch and make the assumption that any catch, it's offline?

Here's my sample code:

_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();

Cheers!


回答1:


If you use Persistent Connection, it would be easier for you to find out if it's connected or not. If you want to use Hub instead of Persistent Connection, I'm not sure how to check.

Below example is using Persistent Connection to check for the connection before start().

Persistent Connection

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
            });
});

Mapping Persistent Connection in Startup file

app.MapSignalR<HubPersistentConnection>("/echo");


来源:https://stackoverflow.com/questions/19885207/is-there-a-way-to-check-if-a-signalr-server-hub-is-active-up-ready-accepting-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!