使用SignalR意外发送多条消息

时间:2012-07-31 13:18:04

标签: c# signalr

我是SignalR的新手,但我理解这个概念。

我的目标是公开调用后会更新所有连接客户端的Web服务。我已经建立了一个小型的淘汰赛连接到集线器并且运行良好。当我点击我的开始按钮时,它会向每个连接的客户端发送一条消息,就像它应该的那样。这是背景的代码。

集线器:

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

问题:

当我打电话给&#34;更新&#34;来自我的控制器的方法(Home / Update,还不是真正的API),它为每个连接的客户端发送一个信号。因此,如果我连接了2个客户端,我将得到2&#34;来自服务器&#34;给每个客户的消息等等。我只想要那个......

有什么建议吗?一切都很赞赏

谢谢,

马特

1 个答案:

答案 0 :(得分:0)

解决方案:

必须导入'使用SignalR.Client;'

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

以下是我找到解决方案的地方:

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

我希望这可以帮助别人。

马特

相关问题