0
votes

I'm new to SignalR but I understand the concept.

My goal is to expose web services which when called will update all connected clients. I've built a little knockout js to connect to the hub and that works well. When I click my start button it sends a message to each of the clients connected like it is supposed to. Here is the code for a background.

Hub:

[HubName("realTimeData")]
public class RealTimeDataHub : Hub
{
    public void UpdateFlash(string message)
    {
        Clients.flashUpdated(message);
    }
    public void clear()
    {
        Clients.cleared();
    }
}

JS:

function viewModel(){
    var self = this;

    self.messages = ko.observableArray([]);

    self.hub = $.connection.realTimeData;

    self.hub.flashUpdated = function (m) {
        self.messages.push(new message(m));
    };
    self.hub.cleared = function () {
        self.messages.removeAll();
    };
    self.Start = function () {          
        self.hub.updateFlash("Updated Flashed from client");
    };
    self.Stop = function () {
        self.hub.clear();
    };
    $.connection.hub.start();
}

ko.applyBindings(new viewModel());

MVC API:

public class HomeController : Controller
{
    public ActionResult Update()
    {
        GetClients().updateFlash("From server");

        return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
    }

    private static dynamic GetClients()
    {
        return GlobalHost.ConnectionManager.GetHubContext<RealTimeData.Hubs.RealTimeDataHub>().Clients;
    }
}

The problem:

When I call the "Update" method from my controller (Home/Update, not a real API yet) it sends one signal for each of the clients connected. So if I have 2 clients connected, I will get 2 "From Server" messages to each client and so on. I would only like the one...

Any suggestions? Anything is appreciated

Thanks,

Matt

1

1 Answers

0
votes

Solution:

Must import 'using SignalR.Client;'

public ActionResult Update()
{
    hub.Invoke("UpdateFlash", "From the Home Controller");
    //GetClients().updateFlash("From server");
    return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}

Here is where I found the solution:

https://github.com/SignalR/SignalR/wiki/SignalR-Client-Hubs

I hope this can help somebody out.

Matt