从服务器到客户端的SignalR通知

时间:2014-02-08 12:06:48

标签: asp.net signalr

我想从服务器向客户端发送通知。我已经尝试了聊天教程 found here,但这只是将聊天消息从一个客户端发送到客户端

我想要的是一个按钮,其onClick方法在服务器上运行。有一次,我单击此按钮,必须将通知(字符串消息)发送给所有客户端。

我的Hub类是

 public class NotificationsHub : Hub
{
    public void SendNotification(string author, string message)
    {
        Clients.All.broadcastNotification(author, message);
    }
} 

并点击按钮,我试试这个

var context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.SendNotification("Admin", "stop the chat");  

但是,我还是无法通知客户。什么都没发生。我究竟做错了什么??

我在客户端网页上的JS通知就像这样

 <script type="text/javascript">
    $(function () {


        // Declare a proxy to reference the hub. 
        var notifications = $.connection.notificationsHub;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.broadcastNotification = function (name, message) {
            alert(name + " says '" + message + "'");

        };

1 个答案:

答案 0 :(得分:3)

您需要在按钮点击功能中调用broadcastNotification,如下所示:

var context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.broadcastNotification("Admin", "stop the chat");

此外,您需要通过添加$.connection.hub.start()启动集线器,您的JS文件应该像:

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.signalR-2.0.1.js"></script>
<script src="/signalr/hubs"></script>

 <script type="text/javascript">   
  $(function () {
       var notifications = $.connection.notificationsHub;
        notifications.client.broadcastNotification = function (name, message) {
            alert(name + " says '" + message + "'");
        $.connection.hub.start();
   };
</script>