Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal R client - Xamarin Forms- Connection Hub is not working C#

Why does the following code does not connect me to the hub?

**** I am Not using Azure Functions ****

Where do I put the azure key?

How can I build this complex Url?

This is similar to my original azure key AccessKey=09988588488378383azudjGHG/E=&Version=1123.0";

I know the server and the hub is working because I created the sample using Java and it is working (see my implementation below).

All I get is "disconnected", no matter what URL I tried.

public event EventHandler<MessageEventArgs> OnReceivedMessage;
public void bindConnectionMessage(bool useHttps)
{
    string urlRoot = "test.signalr.net/?AccessKey=Iwillneversharethiskeyjajajajaj####/E=&Version=1123.0";
    var url = $"http{(useHttps ? "s" : string.Empty)}://{urlRoot}/ChatHub";

    hubConnection =
     new HubConnectionBuilder().WithUrl
     (url)
     .Build();



    hubConnection.On<string>("Send", (message) =>
    {
        var finalMessage = $"Sending something {message}";
        OnReceivedMessage?.Invoke(this, new MessageEventArgs(finalMessage));

    });

    hubConnection.On<string>("Echo", (message) =>
    {
        var finalMessage = $"says {message}";
        OnReceivedMessage?.Invoke(this, new MessageEventArgs(finalMessage));

    });

    hubConnection.StartAsync();
    Debug.WriteLine(IsConnected);
}
like image 830
Pxaml Avatar asked Aug 01 '19 21:08

Pxaml


1 Answers

The start method is asynchronous, you need to add async to the method and await the call.

public async void bindConnectionMessage(bool useHttps)
{
 .....
 await hubConnection.StartAsync();

and you should be good.

Here is my full helper function:

public static HubConnection Create(string serverUri, string hubName, Func<Task<string>> getToken)
    {
        var server = $"https://{serverUri}/{hubName}"; 
        var hubConnection = new HubConnectionBuilder()
            .WithUrl(server, options => {
                options.AccessTokenProvider = getToken;
            })
            .Build();
        return hubConnection; 
    }
like image 192
Christopher Richmond Avatar answered Nov 08 '22 17:11

Christopher Richmond