简体   繁体   中英

C# Console Application to test SignalR Groups

I have a SignalR hub to send group notification, I want to test SignalR Groups. Below is the Hub server code :

[HubName("MyHubServer")]
public class HubServer : Hub
{
    public override Task OnConnected()
    {
        // My code OnConnected
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        // My code OnDisconnected
        return base.OnDisconnected(stopCalled);
    }

    public string JoinGroup(string connectionId, string groupName)
    {
        Groups.Add(connectionId, groupName).Wait();
        return connectionId + " joined " + groupName;
    }

    public string LeaveGroup(string connectionId, string groupName)
    {
        Groups.Remove(connectionId, groupName).Wait();
        return connectionId + " removed " + groupName;
    }

    public string LeaveGroup(string connectionId, string groupName, string customerId = "0")
    {
        Groups.Remove(connectionId, customerId).Wait();
        return connectionId + " removed " + groupName;
    }
}

Server Code to send message to Group (I'll call this code to send message to group after joining group) :

Hub.Clients.Group("Associate").BroadcastAssociateNotification(JsonConvert.SerializeObject(notifications));

Now I want to test SignalR server Group to join group and receive message as server sends message to that group. Below is the code I'm using to test the same, with this code I'm getting error as "A task was canceled" at line Groups.Add(connectionId, groupName).Wait();

static void Main(string[] args)
{
    MainAsync().Wait();
    Console.ReadLine();
}

static async Task MainAsync()
{
    try
    {
        var hubConnection = new HubConnection("http://localhost:12923/");
        IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("MyHubServer");
        stockTickerHubProxy.On<string>("Associate", data => Console.WriteLine("Notification received : ", data));
        hubConnection.Start().Wait();

        await stockTickerHubProxy.Invoke("JoinGroup", "123456", "Associate");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

You are mixing async and blocking calls ( .Wait ) which can lead to deadlocks within the method. You should await throughout and not block on it.

First update Hub to be async all the way

[HubName("MyHubServer")]
public class HubServer : Hub {
    public override Task OnConnected() {
        // My code OnConnected
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled) {
        // My code OnDisconnected
        return base.OnDisconnected(stopCalled);
    }

    public async Task<string> JoinGroup(string connectionId, string groupName) {
        await Groups.Add(connectionId, groupName);
        return connectionId + " joined " + groupName;
    }

    public async Task<string> LeaveGroup(string connectionId, string groupName) {
        await Groups.Remove(connectionId, groupName);
        return connectionId + " removed " + groupName;
    }

    public async Task<string> LeaveGroup(string connectionId, string groupName, string customerId = "0") {
        await Groups.Remove(connectionId, customerId);
        return connectionId + " removed " + groupName;
    }
}

Next, do the same in the console except for the main call.

static async Task MainAsync() {
    try {
        var hubConnection = new HubConnection("http://localhost:12923/");
        IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("MyHubServer");
        stockTickerHubProxy.On<string>("Associate", data => Console.WriteLine("Notification received : ", data));

        await hubConnection.Start();

        await stockTickerHubProxy.Invoke("JoinGroup", "123456", "Associate");
    } catch (Exception ex) {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

once the client is able to make a connection everything should behave as expected.

The following self hosted example was tested to show that the there was communication between the client and hub.

[HubName("MyHubServer")]
public class HubServer : Hub {
    public override Task OnConnected() {
        // My code OnConnected
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled) {
        // My code OnDisconnected
        return base.OnDisconnected(stopCalled);
    }

    public async Task<string> JoinGroup(string connectionId, string groupName) {
        await Groups.Add(connectionId, groupName);
        var message= connectionId + " joined " + groupName;
        Clients.Group("Associate").Notify(message);
        return message;
    }

    public async Task<string> LeaveGroup(string connectionId, string groupName) {
        await Groups.Remove(connectionId, groupName);
        return connectionId + " removed " + groupName;
    }

    public async Task<string> LeaveGroup(string connectionId, string groupName, string customerId = "0") {
        await Groups.Remove(connectionId, customerId);
        return connectionId + " removed " + groupName;
    }
}

class Program {
    static void Main(string[] args) {
        string url = "http://localhost:8080";
        using (WebApp.Start(url)) {
            Console.WriteLine("Server running on {0}", url);
            MainAsync(url).Wait();
            Console.ReadLine();
        }
    }

    static async Task MainAsync(string url) {
        try {
            var hubConnection = new HubConnection(url);
            IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("MyHubServer");
            stockTickerHubProxy.On<string>("Notify",
                data => Console.WriteLine("Notification received : {0}", data));

            await hubConnection.Start();

            var connectionId = hubConnection.ConnectionId;

            var response = await stockTickerHubProxy.Invoke<string>("JoinGroup", connectionId, "Associate");
            Console.WriteLine("Response received : {0}", response);
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        }
    }
}

class Startup {
    public void Configuration(IAppBuilder app) {
        //app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

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