简体   繁体   中英

SignalR 2 StartAsync never returns

In the following part of a class, StartAsync never returns.

Any ideas why? The server appears to be working fine, and works with Javascript clients.

SignalR client version is v1.0.0-rc1-final

    public HubUtil(string baseUrl) //string clientId
    {
        connection = new HubConnectionBuilder()
            .AddJsonProtocol()
            .WithUrl(baseUrl)  // baseUrl is "https://hostname/hubname"
            .Build();

        connection.Closed += Connection_Closed;
        StartIfNeededAsync();
    }

    private Task Connection_Closed(Exception arg)
    {
        return StartIfNeededAsync();
    }

    public async Task StartIfNeededAsync()
    {
        if (_connectionState == ConnectionState.Connected)
        {
            return;
        }

        try
        {
            await connection.StartAsync(); // Never connects
            _connectionState = ConnectionState.Connected;
        }
        catch (Exception ex)
        {
            _connectionState = ConnectionState.Faulted;
            throw;
        }
    }

From a basic console app this is how hubutil is called:

    static void Main(string[] args)
    {
        var hub = new HubUtil("https://host/hubname");
        hub.Invoke("checkin", "id", "");
    }

Probably trying to do too many things at the same time.

Remove StartIfNeededAsync from constructor

public HubUtil(string baseUrl) {
    connection = new HubConnectionBuilder()
        .AddJsonProtocol()
        .WithUrl(baseUrl)  // baseUrl is "https://hostname/hubname"
        .Build();

    connection.Closed += Connection_Closed;       
}

private Task Connection_Closed(Exception arg) {
    return StartIfNeededAsync();
}

public async Task StartIfNeededAsync() {
    if (_connectionState == ConnectionState.Connected) {
        return;
    }

    try {
        await connection.StartAsync();
        _connectionState = ConnectionState.Connected;
    } catch (Exception ex) {
        _connectionState = ConnectionState.Faulted;
        throw;
    }
}

//...

and make it an explicit call also taking SSL into consideration.

//Handle TLS protocols
System.Net.ServicePointManager.SecurityProtocol =
    System.Net.SecurityProtocolType.Tls
    | System.Net.SecurityProtocolType.Tls11
    | System.Net.SecurityProtocolType.Tls12;

var hub = new HubUtil("https://host/hubname");
await hub.StartIfNeededAsync();
hub.Invoke("checkin", "id", "");

I answered a similar question on SO already. I don't want to copy and paste it here so here is the link instead:

https://stackoverflow.com/a/58551924/603807

Since this is a link to my own answer on the SO site I would hope this takes a pass for the moderators who don't like link only answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM