从服务器到客户端的SignalR通知 [英] SignalR notification from server to client

查看:119
本文介绍了从服务器到客户端的SignalR通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将通知从服务器推送到客户端.我已经尝试过聊天教程

I want to push a notification from my server to client. I've tried the chat tutorial found here but this just sends chat messages from one client to client

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

What I want is a button whose onClick method is running at server. Once, I click this button, notifications (a string message) must be sent to all clients.

我的Hub类是

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

然后点击按钮,我尝试一下

and in the button click, I try this

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

但是,我仍然无法通知客户.没事我究竟做错了什么??

But still, I'm not able to notify the clients. Nothing is happening. What am I doing wrong??

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

My JS at client web page to notify is like this

 <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 + "'");

        };

推荐答案

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

You need to call broadcastNotification in your button click function, like below:

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

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

Also, you need to start the hub by adding $.connection.hub.start(), your JS file should be like:

<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>

这篇关于从服务器到客户端的SignalR通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆